-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.coffee
363 lines (293 loc) · 9.03 KB
/
app.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
express = require('express')
mustache = require("./mustache.js");
io = require('socket.io')
redis = require('redis')
redis_store = require('connect-redis')(express)
bcrypt = require('bcrypt')
crypto = require('crypto')
hash = (txt) ->
crypto.createHash('sha256').update(txt).encoding('hex')
tmpl =
compile: (source,options) ->
if 'string' == typeof source
(options) ->
options.locals = options.locals || {}
options.partials = options.partials || {}
if options.body then locals.body = options.body
compile_options = {}
template = mustache.compile source, compile_options
template options.locals,options.partials
else
source
render: (template,options) ->
template = this.compile(template,options)
template(options)
app = module.exports = express.createServer()
viewPath = () -> __dirname + '/views'
app.configure () ->
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.session {secret:'ze zecret goes here',store:new redis_store()}
app.use express.methodOverride()
app.use app.router
app.set 'views', viewPath()
app.set 'view options', {layout:false}
app.register '.html',tmpl
app.use express.errorHandler({
dumpExceptions: true
showStack: true
})
app.use express.static(__dirname+'/public')
sessions = {}
rc = redis.createClient()
EH = (resp) ->
(e) ->
resp.json e,500
generateID = (prefix,cb) ->
rc.incr prefix, (e,uk) ->
cb e,uk
###
generateUser = (e,cb) ->
generateID 'userkey',e,() ->
rc.incr 'userkey',(e,uk) ->
rc.hset 'uk:' + uk,'userkey',uk
rc.lpush 'global.users',uk
cb uk
###
ERR = (msg) ->
{'message':msg}
createRoom = (details,cb) ->
if not details.name then cb ERR 'No name specified for the room'
if not details.created_userkey then cb ERR 'No created user specified'
name = details.name
uk = details.created_userkey
await generateID 'room',defer e,rk
if e? then return cb e
rc.hset 'room:' + rk,'roomkey',rk
rc.hset 'room:' + rk,'created_userkey',uk
rc.hset 'room:' + rk,'name',name
rc.sadd 'room.users:' + rk,uk
cb null,rk
roomHasUser = (rk,uk,cb) ->
await rc.sismember 'room.users:' + rk,uk,defer e,exists
if e? then return cb e
return cb null,exists==1
createUser = (details,cb) ->
if not details.email then return cb ERR 'No email address specified'
email = details.email
await rc.sismember 'emails',email,defer e,exists
if exists == 1 then return cb ERR "Email address #{email} exists"
await rc.sadd 'emails',email,defer e,ok
await generateID 'userkey',defer e,uk
if e? then return cb e,null
await bcrypt.genSalt 10, defer e,salt
if e? then return cb e,null
console.log 'my salt',salt
await bcrypt.hash details.password,salt,defer e,hash
if e? then return cb e,null
rc.hset 'user:' + uk,'userkey',uk
rc.hset 'user:' + uk,'name',details.name
rc.hset 'user:' + uk,'password',hash
rc.hset 'user:' + uk,'email',email
rc.set 'useremail:' + email,uk
user =
userkey: uk
name: details.name
password: hash
email: email
return cb null,user
createAccount = (details,cb) ->
account = details.accountid
uk = details.userkey
if not account then cb ERR 'No account name specified'
if not uk then cb ERR 'No user associated with the account'
await rc.sismember 'accounts',account,defer e,exists
if e? then return cb e
if exists ==1 then return cb ERR 'An account with this name already exists'
rc.hmset 'account:' + account,{'accountid':account,'created_userkey':uk}
rc.sadd 'accountusers:' + account,uk
cb null,account
createPendingAction = (action,details,cb) ->
await rc.generateID 'action',defer e,key
if e? then cb e
h = hash key
awat rc.hmset 'action:' + h,details,defer e,whatever
if e? then cb e
cb null,hash
executePendingAction = (actionhash,cb) ->
await rc.hgetall 'action:' + actionhash,defer e,details
if not e? then cb e
if not details then cb ERR 'Invalid Action'
executeAction details,cb
executeAction = (details,cb) ->
switch details.action
when 'useraccountlink'
accountid = details.accountid
uk = details.uk
if not accountid? then cb ERR 'Invalid Account'
if not uk? then cb ERR 'Invalid user for account'
return linkUserToAccount accountid,uk,cb
else
cb ERR 'Invalid action:' + details.action
linkUserToAccount = (accountid,uk,cb) ->
await rc.sismember 'accounts',accountid,defer e,exists
if e? then cb e
if exists!=1 then cb ERR 'Invalid account:' + accountid
await getUserDetails uk,defer e,userdetails
if e? then cb e
if not userdetails then cb ERR 'Invalid user'
rc.sadd 'accountusers:' + accountid,uk,cb
getUserDetails = (uk,cb) ->
rc.hgetall 'user:' + uk,cb
verifyUser = (email,password,cb) ->
await rc.get 'useremail:' + email, defer e,uk
if e? then return cb e,null
if not uk then return cb ERR 'No such user'
await rc.hgetall 'user:' + uk,defer e,user
if e? then return cb e,null
actual_password = user.password
await bcrypt.compare password,actual_password, defer e,ok
if e? then return cb e,null
if not ok then return cb ERR 'Invalid email address or password'
cb null,user
createUserSession = (uk,cb) ->
await generateID 'session',defer e,sid
if e? then return cb e
#TODO: expiry?
rc.set 'sesssion:' + sid,uk,defer e,r
if e? then return cb e
return cb null,sid
getUserDetails = (uk,cb,err_cb) ->
rc.hgetall 'uk:' + uk,(err,obj) ->
if err?
if err_cb? then err_cb err
else
cb(obj)
fillMessageData = (messages,cb) ->
console.log 'fillin message',messages
multi = rc.multi()
uklist = {}
for msg in messages
if uklist[msg.userkey]? then continue
multi.hgetall 'user:' + msg.userkey
uklist[msg.userkey] = '1'
multi.exec (err,replies) ->
i = 0
console.log 'multireplies',replies
ukmap = {}
for r in replies
ukmap[r.userkey] = r.name
for msg in messages
messages[i].username = ukmap[messages[i].userkey]
i += 1
cb(messages)
pushMessage = (message) ->
chid = message.chid
if not sessions[chid]? then return
fillMessageData [message],(messages) ->
for s in sessions[chid]
for m in messages
s.emit 'message',m
io = io.listen app
io.sockets.on 'connection', (socket) ->
socket.on 'connect',(data) ->
chid = data.chid
if not sessions[chid]
sessions[chid] = []
sessions[chid].push socket
socket.on 'message',(data) ->
chid = data.chid
rc.lpush 'session:' + chid,JSON.stringify data
pushMessage data
app.get '/', (req,resp) ->
resp.render 'index.html'
app.post '/createuser', (req,resp) ->
un = req.query.name
pwd = req.query.password
email = req.query.email
await createUser {name:un,password:pwd,email:email},defer e,user
if e?
resp.json e,500
return
resp.json user
authUser = (req,resp,next) ->
s = req.session?.sessionid
if not s?
req.session?.sessionid = null
req.session?.user = null
resp.redirect('/login?next=' + encodeURIComponent(req.path))
else
next()
app.get '/:chid/history', (req,resp) ->
chid = req.params.chid
history = []
rc.lrange 'session:' + chid,0,100,(e,objlist) ->
if e?
console.log 'Error',e
resp.json e
return
else
objlist = (JSON.parse obj for obj in objlist)
fillMessageData objlist,(messages) ->
for obj in messages
history.push obj
resp.json history
app.get '/login', (req,resp) ->
next = req.query.next
resp.render 'login.html',{locals:{next:next}}
app.post '/login', (req,resp) ->
console.log req.body
login = req.body.login
next = req.body.next
pwd = req.body.password
await verifyUser login,pwd,defer e,user
console.log 'user verified',e,user
if e?
resp.render 'login.html',{locals:{'error':e,'login':login,next:next}}
return
await createUserSession user.userkey,defer e,sid
if e?
resp.render 'login.html',{locals:{'error':e,'login':login,next:next}}
return
req.session.user = user
req.session.sessionid = sid
resp.redirect(next)
app.post '/signup', (req,resp) ->
login = req.body.newlogin
password = req.body.newpassword
name = req.body.newname
next = req.body.next
err_handler = (e) ->
resp.render 'login.html',{locals:{newlogin:login,newname:name,next:next,signuperror:e}}
if not name then return err_handler ERR 'Name is required'
if not login then return err_handler ERR 'A valid email address is required'
await createUser {'name':name,'email':login,password:password}, defer e,user
if e? then return err_handler e
await createUserSession user.userkey,defer e,sid
if e? then return err_handler e
req.session.user = user
req.session.sessionid = sid
resp.redirect next
app.get '/:chid', authUser,(req,resp) ->
handler = (req,resp) ->
ch_id = req.params.chid
history = []
rc.lrange 'session:' + ch_id,0,10,(e,objlist) ->
if e?
console.log 'Error',e
else
for obj in objlist
history.push
'item':obj
resp.render 'ch.html', {locals:{'chid':ch_id,'userkey':req.session.user.userkey,'user':req.session.user ? {}}}
console.log 'got user key',req.session.userkey
handler req,resp
###
createUser {'name':'hs','password':'password','email':'[email protected]'},(e,details) ->
if e? then console.log 'Error',e
else console.log 'created user',details
await verifyUser '[email protected]','pas1sword',defer e,user
if e? then console.log 'Error',e
else console.log 'Valid User',user
###
app.listen 81