forked from jslatts/nodechat-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodechat-tutorial.html
11149 lines (9167 loc) · 359 KB
/
nodechat-tutorial.html
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<title>nodechat-tutorial</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style>body {
margin: 0;
padding: 0;
font: 14px/1.5 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif;
color: #252519;
}
a {
color: #252519;
}
a:hover {
text-decoration: underline;
color: #19469D;
}
p {
margin: 12px 0;
}
h1, h2, h3 {
margin: 0;
padding: 0;
}
table#source {
width: 100%;
border-collapse: collapse;
}
table#source td:first-child {
padding: 30px 40px 30px 40px;
vertical-align: top;
}
table#source td:first-child,
table#source td:first-child pre {
width: 450px;
}
table#source td:last-child {
padding: 30px 0 30px 40px;
border-left: 1px solid #E5E5EE;
background: #F5F5FF;
}
table#source tr {
border-bottom: 1px solid #E5E5EE;
}
table#source tr.filename {
padding-top: 40px;
border-top: 1px solid #E5E5EE;
}
table#source tr.filename td:first-child {
text-transform: capitalize;
}
table#source tr.filename td:last-child {
font-size: 12px;
}
table#source tr.filename h2 {
margin: 0;
padding: 0;
cursor: pointer;
}
table#source tr.code h1,
table#source tr.code h2,
table#source tr.code h3 {
margin-top: 30px;
font-family: "Lucida Grande", "Helvetica Nueue", Arial, sans-serif;
font-size: 18px;
}
table#source tr.code h2 {
font-size: 16px;
}
table#source tr.code h3 {
font-size: 14px;
}
table#source tr.code ul {
margin: 15px 0 15px 35px;
padding: 0;
}
table#source tr.code ul li {
margin: 0;
padding: 1px 0;
}
table#source tr.code ul li p {
margin: 0;
padding: 0;
}
table#source tr.code td:first-child pre {
padding: 20px;
}
#ribbon {
position: fixed;
top: 0;
right: 0;
}
code .string { color: #219161; }
code .regexp { color: #219161; }
code .keyword { color: #954121; }
code .number { color: #19469D; }
code .comment { color: #bbb; }
code .this { color: #19469D; }</style>
<script>
$(function(){
$('tr.code').hide();
$('tr.filename').toggle(function(){
$(this).nextUntil('.filename').fadeIn();
}, function(){
$(this).nextUntil('.filename').fadeOut();
});
});
</script>
</head>
<body>
<table id="source"><tbody><tr><td><h1>nodechat-tutorial</h1><p>Tutorial code to go along with fzysqr.com post at http://fzysqr.com/2011/03/27/nodechat-js-continued-authentication-profiles-ponies-and-a-meaner-socket-io/</p></td><td></td></tr><tr class="filename"><td><h2 id="core.js"><a href="#">core</a></h2></td><td>core.js</td></tr><tr class="code">
<td class="docs">
<p>Include core dependencies.<br></br> </p>
</td>
<td class="code">
<pre><code><span class="keyword">var</span> <span class="variable">_</span> = <span class="variable">require</span>(<span class="string">'underscore'</span>).<span class="variable">_</span>
, <span class="class">Backbone</span> = <span class="variable">require</span>(<span class="string">'backbone'</span>);</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Include our own modules
</p>
</td>
<td class="code">
<pre><code><span class="keyword">var</span> <span class="variable">models</span> = <span class="variable">require</span>(<span class="string">'./models/models'</span>)
, <span class="variable">auth</span> = <span class="variable">require</span>(<span class="string">'./lib/auth'</span>);</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Require redis and setup the client
</p>
</td>
<td class="code">
<pre><code><span class="keyword">var</span> <span class="variable">redis</span> = <span class="variable">require</span>(<span class="string">'redis'</span>)
, <span class="variable">rc</span> = <span class="variable">redis</span>.<span class="variable">createClient</span>();
<span class="variable">rc</span>.<span class="variable">on</span>(<span class="string">'error'</span>, <span class="keyword">function</span> (<span class="variable">err</span>) {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Error '</span> + <span class="variable">err</span>);
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Setup connect, express, socket, and the connect-redis session store
</p>
</td>
<td class="code">
<pre><code><span class="keyword">var</span> <span class="variable">express</span> = <span class="variable">require</span>(<span class="string">'express'</span>)
, <span class="variable">app</span> = <span class="variable">express</span>.<span class="variable">createServer</span>()
, <span class="variable">connect</span> = <span class="variable">require</span>(<span class="string">'connect'</span>)
, <span class="variable">jade</span> = <span class="variable">require</span>(<span class="string">'jade'</span>)
, <span class="variable">socket</span> = <span class="variable">require</span>(<span class="string">'socket.io'</span>).<span class="variable">listen</span>(<span class="variable">app</span>)
, <span class="class">RedisStore</span> = <span class="variable">require</span>(<span class="string">'connect-redis'</span>);
<span class="variable">app</span>.<span class="variable">set</span>(<span class="string">'view engine'</span>, <span class="string">'jade'</span>);
<span class="variable">app</span>.<span class="variable">set</span>(<span class="string">'view options'</span>, {<span class="variable">layout</span>: <span class="variable">false</span>});
<span class="variable">app</span>.<span class="variable">use</span>(<span class="variable">express</span>.<span class="variable">bodyParser</span>());
<span class="variable">app</span>.<span class="variable">use</span>(<span class="variable">express</span>.<span class="variable">cookieParser</span>());
<span class="variable">app</span>.<span class="variable">use</span>(<span class="variable">express</span>.<span class="variable">session</span>({ <span class="variable">store</span>: <span class="keyword">new</span> <span class="class">RedisStore</span>(), <span class="variable">secret</span>: <span class="string">'Secretly I am an elephant'</span> }));</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<h2>Route GET /login</h2>
<h2>Template login.jade</h2>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">get</span>(<span class="string">'/login'</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">res</span>.<span class="variable">render</span>(<span class="string">'login'</span>);
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<h2>Route POST /login</h2>
<p>Calls the authentication module to verify login details. Failures are redirected back to the login page.</p>
<p>If the authentication module gives us a user object back, we ask connect to regenerate the session and send the client back to index. Note: we specify a <em>long</em> cookie age so users won't have to log in frequently. We also set the httpOnly flag to false (I know, not so secure) to make the cookie available over <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html">Flash Sockets</a>.
</p>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">post</span>(<span class="string">'/login'</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">auth</span>.<span class="variable">authenticateUser</span>(<span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">username</span>, <span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">password</span>, <span class="keyword">function</span> (<span class="variable">err</span>, <span class="variable">user</span>) {
<span class="keyword">if</span> (<span class="variable">user</span>) {
<span class="comment">// Regenerate session when signing in to prevent fixation </span>
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">regenerate</span>(<span class="keyword">function</span> () {
<span class="comment">// Store the user's primary key in the session store to be retrieved, or in this case the entire user object</span>
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'regenerated session id '</span> + <span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">id</span>);
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">cookie</span>.<span class="variable">maxAge</span> = <span class="number integer">100</span> * <span class="number integer">24</span> * <span class="number integer">60</span> * <span class="number integer">60</span> * <span class="number integer">1000</span>; <span class="comment">//Force longer cookie age</span>
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">cookie</span>.<span class="variable">httpOnly</span> = <span class="variable">false</span>;
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">user</span> = <span class="variable">user</span>;
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Storing new hash for user '</span> + <span class="variable">user</span>.<span class="variable">get</span>(<span class="string">'name'</span>) + <span class="string">': '</span> + <span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">user</span>.<span class="variable">get</span>(<span class="string">'hashPass'</span>));
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'/'</span>);
});
} <span class="keyword">else</span> {
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">error</span> = <span class="string">'Authentication failed, please check your username and password.'</span>;
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'back'</span>);
}
});
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<h2>Route GET /signup:</h2>
<h2>Template signup.jade</h2>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">get</span>(<span class="string">'/signup'</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">res</span>.<span class="variable">render</span>(<span class="string">'signup'</span>);
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<h2>Route POST /signup</h2>
<p>Calls createNewUserAccount() in the auth module, redirects to /login if a user object is returned. Redirects to /signup if not.
</p>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">post</span>(<span class="string">'/signup'</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">auth</span>.<span class="variable">createNewUserAccount</span>(<span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">username</span>, <span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">password1</span>, <span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">password2</span>, <span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">email</span>, <span class="variable">req</span>.<span class="variable">body</span>.<span class="variable">ponies</span>, <span class="keyword">function</span> (<span class="variable">err</span>, <span class="variable">user</span>) {
<span class="keyword">if</span> ((<span class="variable">err</span>) || (!<span class="variable">user</span>)) {
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">error</span> = <span class="string">'New user failed, please check your username and password.'</span>;
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'back'</span>);
}
<span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable">user</span>) {
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'/login'</span>);
}
});
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p> Tell connect to destory the session.
</p>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">get</span>(<span class="string">'/logout'</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">destroy</span>(<span class="keyword">function</span> () {
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'home'</span>);
});
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Serve up any static file requested by the client</p>
<h2>TODO should restrict this to only server *public* routes.</h2>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">get</span>('</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>.(js|css)', function (req, res) {
res.sendfile('./' + req.url);
});</p>
<p>/*
Middleware that decides what a valid login looks like. In this case, just verify that we have a session object for the user.</p>
<p> This is an express <a href="http://expressjs.com/guide.html#route-middleware">route middleware</a>. Control is passed to the middleware function before the route function is called. We use restrictAccess() to verify that we have a valid user key in the session, implying that authentication has succeeded, before we send the client to the index.jade template. If we do not have a valid user in the session, then we redirect to the '/login' route. This effectively locks down our '/' route from unauthenticated access. You could add the restrictAccess() all to any route you want to protect.
</p>
</td>
<td class="code">
<pre><code><span class="keyword">function</span> <span class="variable">restrictAccess</span>(<span class="variable">req</span>, <span class="variable">res</span>, <span class="variable">next</span>) {
<span class="keyword">if</span> (<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">user</span>) {
<span class="variable">next</span>();
} <span class="keyword">else</span> {
<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">error</span> = <span class="string">'Access denied!'</span>;
<span class="variable">res</span>.<span class="variable">redirect</span>(<span class="string">'/login'</span>);
}
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Server up the main index view. </p>
<p>Calls the restrictAccess() middleware.</p>
<p> </p>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">get</span>(<span class="string">'/'</span>, <span class="variable">restrictAccess</span>, <span class="keyword">function</span> (<span class="variable">req</span>, <span class="variable">res</span>) {
<span class="variable">res</span>.<span class="variable">render</span>(<span class="string">'index'</span>, {
<span class="variable">locals</span>: { <span class="variable">name</span>: <span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">user</span>.<span class="variable">name</span>, <span class="variable">hashPass</span>: <span class="class">JSON</span>.<span class="variable">stringify</span>(<span class="variable">req</span>.<span class="variable">session</span>.<span class="variable">user</span>.<span class="variable">hashPass</span>) }
});
});
<span class="comment">//create local state</span>
<span class="keyword">var</span> <span class="variable">activeClients</span> = <span class="number integer">0</span>;
<span class="keyword">var</span> <span class="variable">nodeChatModel</span> = <span class="keyword">new</span> <span class="variable">models</span>.<span class="class">NodeChatModel</span>();</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>When we have a client that shouldn't be connected, <strong>kick 'em off!</strong>' </p>
<h2></h2>
<ul><li><p><strong>param</strong>: <em>object</em> client</p></li><li><p><strong>param</strong>: <em>function</em> fn</p></li></ul>
</td>
<td class="code">
<pre><code><span class="keyword">function</span> <span class="variable">disconnectAndRedirectClient</span>(<span class="variable">client</span>, <span class="variable">fn</span>) {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Disconnecting unauthenticated user'</span>);
<span class="variable">client</span>.<span class="variable">send</span>({ <span class="variable">event</span>: <span class="string">'disconnect'</span> });
<span class="variable">client</span>.<span class="variable">connection</span>.<span class="variable">end</span>();
<span class="keyword">return</span> <span class="variable">fn</span>();
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Event handler for client disconnects. Simply broadcasts the new active client count.</p>
<h2></h2>
<ul><li><p><strong>param</strong>: <em>object</em> client</p></li></ul>
</td>
<td class="code">
<pre><code><span class="keyword">function</span> <span class="variable">clientDisconnect</span>(<span class="variable">client</span>) {
<span class="variable">activeClients</span> -= <span class="number integer">1</span>;
<span class="variable">client</span>.<span class="variable">broadcast</span>({<span class="variable">clients</span>: <span class="variable">activeClients</span>});
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Event handler for new chat messages. Stores the chat in redis and broadcasts it to all connected clients.</p>
<h2></h2>
<ul><li><p><strong>param</strong>: <em>object</em> client</p></li><li><p><strong>param</strong>: <em>object</em> socket</p></li><li><p><strong>param</strong>: <em>json string</em> msg</p></li></ul>
</td>
<td class="code">
<pre><code><span class="keyword">function</span> <span class="variable">chatMessage</span>(<span class="variable">client</span>, <span class="variable">socket</span>, <span class="variable">msg</span>) {
<span class="keyword">var</span> <span class="variable">chat</span> = <span class="keyword">new</span> <span class="variable">models</span>.<span class="class">ChatEntry</span>();
<span class="variable">chat</span>.<span class="variable">mport</span>(<span class="variable">msg</span>);
<span class="variable">rc</span>.<span class="variable">incr</span>(<span class="string">'next.chatentry.id'</span>, <span class="keyword">function</span> (<span class="variable">err</span>, <span class="variable">newId</span>) {
<span class="variable">chat</span>.<span class="variable">set</span>({<span class="variable">id</span>: <span class="variable">newId</span>});
<span class="variable">nodeChatModel</span>.<span class="variable">chats</span>.<span class="variable">add</span>(<span class="variable">chat</span>);
<span class="keyword">var</span> <span class="variable">expandedMsg</span> = <span class="variable">chat</span>.<span class="variable">get</span>(<span class="string">'id'</span>) + <span class="string">' '</span> + <span class="variable">client</span>.<span class="variable">user</span>.<span class="variable">name</span> + <span class="string">': '</span> + <span class="variable">chat</span>.<span class="variable">get</span>(<span class="string">'text'</span>);
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'('</span> + <span class="variable">client</span>.<span class="variable">sessionId</span> + <span class="string">') '</span> + <span class="variable">expandedMsg</span>);
<span class="variable">rc</span>.<span class="variable">rpush</span>(<span class="string">'chatentries'</span>, <span class="variable">chat</span>.<span class="variable">xport</span>(), <span class="variable">redis</span>.<span class="variable">print</span>);
<span class="variable">socket</span>.<span class="variable">broadcast</span>({
<span class="variable">event</span>: <span class="string">'chat'</span>,
<span class="variable">data</span>: <span class="variable">chat</span>.<span class="variable">xport</span>()
});
});
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Handle the new connection event for socket. </p>
<p>connectSession() is a helper method that will verify a client's validity by checking for a cookie in the request header, then, if we find it, <em>pulling their session out of redis</em>. </p>
<p>We then use the helper method in the 'connection' handler for our socket listener. Instead accepting any user connection, we are going to check that the client has a valid session (meaning they logged in). If they don't, give them the boot! If they do, then we store a copy of the session data (yay we have access!) in the client object and then setup the rest of the socket events. Finally, send them a welcome message just to prove that we remembered their profile.
</p>
</td>
<td class="code">
<pre><code><span class="variable">socket</span>.<span class="variable">on</span>(<span class="string">'connection'</span>, <span class="keyword">function</span> (<span class="variable">client</span>) {
<span class="variable">client</span>.<span class="variable">connectSession</span> = <span class="keyword">function</span> (<span class="variable">fn</span>) {
<span class="keyword">if</span> (!<span class="variable">client</span>.<span class="variable">request</span> || !<span class="variable">client</span>.<span class="variable">request</span>.<span class="variable">headers</span> || !<span class="variable">client</span>.<span class="variable">request</span>.<span class="variable">headers</span>.<span class="variable">cookie</span>) {
<span class="variable">disconnectAndRedirectClient</span>(<span class="variable">client</span>, <span class="keyword">function</span> () {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Null request/header/cookie!'</span>);
});
<span class="keyword">return</span>;
}
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Cookie is'</span> + <span class="variable">client</span>.<span class="variable">request</span>.<span class="variable">headers</span>.<span class="variable">cookie</span>);
<span class="keyword">var</span> <span class="variable">match</span>, <span class="variable">sid</span>;
<span class="variable">match</span> = <span class="variable">client</span>.<span class="variable">request</span>.<span class="variable">headers</span>.<span class="variable">cookie</span>.<span class="variable">match</span>(<span class="regexp">/connect\.sid=([^;]+)/</span>);
<span class="keyword">if</span> (!<span class="variable">match</span> || <span class="variable">match</span>.<span class="variable">length</span> &<span class="variable">lt</span>; <span class="number integer">2</span>) {
<span class="variable">disconnectAndRedirectClient</span>(<span class="variable">client</span>, <span class="keyword">function</span> () {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Failed to find connect.sid in cookie'</span>);
});
<span class="keyword">return</span>;
}
<span class="variable">sid</span> = <span class="variable">unescape</span>(<span class="variable">match</span>[<span class="number integer">1</span>]);
<span class="variable">rc</span>.<span class="variable">get</span>(<span class="variable">sid</span>, <span class="keyword">function</span> (<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="variable">fn</span>(<span class="variable">err</span>, <span class="class">JSON</span>.<span class="variable">parse</span>(<span class="variable">data</span>));
});
};
<span class="variable">client</span>.<span class="variable">connectSession</span>(<span class="keyword">function</span> (<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span> (<span class="variable">err</span>) {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'Error on connectionSession: '</span> + <span class="variable">err</span>);
<span class="keyword">return</span>;
}
<span class="variable">client</span>.<span class="variable">user</span> = <span class="variable">data</span>.<span class="variable">user</span>;
<span class="variable">activeClients</span> += <span class="number integer">1</span>;
<span class="variable">client</span>.<span class="variable">on</span>(<span class="string">'disconnect'</span>, <span class="keyword">function</span> () {
<span class="variable">clientDisconnect</span>(<span class="variable">client</span>);
});
<span class="variable">client</span>.<span class="variable">on</span>(<span class="string">'message'</span>, <span class="keyword">function</span> (<span class="variable">msg</span>) {
<span class="variable">chatMessage</span>(<span class="variable">client</span>, <span class="variable">socket</span>, <span class="variable">msg</span>);
});
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'User successfully connected with '</span> + <span class="variable">data</span>.<span class="variable">user</span>.<span class="variable">name</span> + <span class="string">' hash '</span> + <span class="variable">data</span>.<span class="variable">user</span>.<span class="variable">hashPass</span>);
<span class="variable">socket</span>.<span class="variable">broadcast</span>({
<span class="variable">event</span>: <span class="string">'update'</span>,
<span class="variable">clients</span>: <span class="variable">activeClients</span>
});
<span class="keyword">var</span> <span class="variable">ponyWelcome</span> = <span class="keyword">new</span> <span class="variable">models</span>.<span class="class">ChatEntry</span>({<span class="variable">name</span>: <span class="string">'PonyBot'</span>, <span class="variable">text</span>: <span class="string">'Hello '</span> + <span class="variable">data</span>.<span class="variable">user</span>.<span class="variable">name</span> + <span class="string">'. I also feel that ponies '</span> + <span class="variable">data</span>.<span class="variable">user</span>.<span class="variable">ponies</span> + <span class="string">'. Welcome to nodechat.js'</span>});
<span class="variable">socket</span>.<span class="variable">broadcast</span>({
<span class="variable">event</span>: <span class="string">'chat'</span>,
<span class="variable">data</span>: <span class="variable">ponyWelcome</span>.<span class="variable">xport</span>()
});
});
});</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Fire up the webserver
</p>
</td>
<td class="code">
<pre><code><span class="variable">app</span>.<span class="variable">listen</span>(<span class="number integer">8000</span>);
</code></pre>
</td>
</tr><tr class="filename"><td><h2 id="controllers/controllers.js"><a href="#">controllers</a></h2></td><td>controllers/controllers.js</td></tr><tr class="code">
<td class="docs">
<p>//
//Controllers
//
var NodeChatController = {
init: function(options) {
this.socket = new io.Socket(null, {port: 8000});
var mysocket = this.socket;
this.userName = options.userName;
this.hashPass = options.hashPass;</p>
<pre><code> this.model = new models.NodeChatModel({userName: this.userName, hashPass: this.hashPass});
this.view = new NodeChatView({model: this.model, socket: this.socket, el: $('#content')});
var view = this.view;
this.socket.on('message', function(msg) {view.msgReceived(msg)});
this.socket.connect();
this.view.render();
return this;
}</code></pre>
<p>};</p>
</td>
<td class="code">
</td>
</tr><tr class="filename"><td><h2 id="lib/auth.js"><a href="#">auth</a></h2></td><td>lib/auth.js</td></tr><tr class="code">
<td class="docs">
<p>This will be a <a href="http://www.commonjs.org/">CommonJS module</a> so we need to start off with some setup. </p>
<p>Here we are checking to see if this code is included as a module. If it is, we go ahead and include our dependencies (in this case, our models lib, redis, and hash + friends). If we are not a module, we may as well explode because the rest of the code won't run without redis and hash.
</p>
</td>
<td class="code">
<pre><code>(<span class="keyword">function</span> () {
<span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="variable">exports</span> !== <span class="string">'undefined'</span>) {
<span class="variable">redis</span> = <span class="variable">require</span>(<span class="string">'redis'</span>);
<span class="variable">rc</span> = <span class="variable">redis</span>.<span class="variable">createClient</span>();
<span class="variable">models</span> = <span class="variable">require</span>(<span class="string">'../models/models'</span>);
<span class="comment">//joose is required to support the hash lib we are using</span>
<span class="variable">require</span>(<span class="string">'joose'</span>);
<span class="variable">require</span>(<span class="string">'joosex-namespace-depended'</span>);
<span class="variable">require</span>(<span class="string">'hash'</span>);
}
<span class="keyword">else</span> {
<span class="keyword">throw</span> <span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'auth.js must be loaded as a module.'</span>);
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Checks to see if the user exists in redis. If it does, it calls verifyUserAccount(). Otherwise callback with an error.</p>
<ul><li><strong>para</strong>: <em>m</em>
: {string} name</li><li><strong>para</strong>: <em>m</em>
: {string} pass</li><li><strong>para</strong>: <em>m</em>
: {function} fn</li><li><strong>ap</strong>: <em>i</em>
: public
</li></ul>
</td>
<td class="code">
<pre><code><span class="variable">exports</span>.<span class="variable">authenticateUser</span> = <span class="keyword">function</span>(<span class="variable">name</span>, <span class="variable">pass</span>, <span class="variable">fn</span>) {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'[authenticate] Starting auth for '</span> + <span class="variable">name</span> + <span class="string">' with password '</span> + <span class="variable">pass</span>);
<span class="keyword">var</span> <span class="variable">rKey</span> = <span class="string">'user:'</span> + <span class="variable">name</span>;
<span class="variable">rc</span>.<span class="variable">get</span>(<span class="variable">rKey</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>){
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[authenticateUser] SET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">' for value: '</span> + <span class="variable">name</span>));
<span class="keyword">if</span> (!<span class="variable">data</span>) {
<span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[authenticateUser] invalid password'</span>));
}
<span class="keyword">else</span> {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'[authenticateUser] user: '</span> + <span class="variable">name</span> + <span class="string">' found in store. Verifying password.'</span>);
<span class="variable">verifyUserAccount</span>(<span class="variable">data</span>, <span class="variable">pass</span>, <span class="variable">fn</span>)
}
});
};</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Steps through the process of retreiving the salt, calculating the hash of the passed in password, then comparing it to the stored hash in redis.</p>
<p>If successful, create a new user model and pass it to the callback.</p>
<p>Otherwise, any failure along the way means we callback with an error.</p>
<p>Assumes the passed in user exists in redis. </p>
<ul><li><strong>para</strong>: <em>m</em>
: {string} foundUserName</li><li><strong>para</strong>: <em>m</em>
: {string} pass</li><li><strong>para</strong>: <em>m</em>
: {function} fn</li><li><strong>ap</strong>: <em>i</em>
: private
</li></ul>
</td>
<td class="code">
<pre><code><span class="keyword">var</span> <span class="variable">verifyUserAccount</span> = <span class="keyword">function</span>(<span class="variable">foundUserName</span>, <span class="variable">pass</span>, <span class="variable">fn</span>) {
<span class="keyword">var</span> <span class="variable">rKey</span> = <span class="string">'user:'</span> + <span class="variable">foundUserName</span>;
<span class="variable">rc</span>.<span class="variable">get</span>(<span class="variable">rKey</span> + <span class="string">'.salt'</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>){
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[verifyUserAccount] GET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.salt'</span>));
<span class="keyword">if</span>(<span class="variable">data</span>) {
<span class="keyword">var</span> <span class="variable">calculatedHash</span> = <span class="class">Hash</span>.<span class="variable">sha512</span>(<span class="variable">data</span> + <span class="string">'_'</span> + <span class="variable">pass</span>);
<span class="variable">rc</span>.<span class="variable">get</span>(<span class="variable">rKey</span> + <span class="string">'.hashPass'</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[verifyUserAccount] GET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.hashPass'</span>));
<span class="keyword">if</span> (<span class="variable">calculatedHash</span> === <span class="variable">data</span>) {
<span class="variable">console</span>.<span class="variable">log</span>(<span class="string">'[verifyUserAccount] Auth succeeded for '</span> + <span class="variable">foundUserName</span> + <span class="string">' with password '</span> + <span class="variable">pass</span>);
<span class="variable">rc</span>.<span class="variable">get</span>(<span class="variable">rKey</span> + <span class="string">'.profile'</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[verifyUserAccount] GET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.profile'</span> + <span class="string">' for user profile'</span>));
<span class="keyword">var</span> <span class="variable">foundUser</span> = <span class="keyword">new</span> <span class="variable">models</span>.<span class="class">User</span>();
<span class="variable">foundUser</span>.<span class="variable">mport</span>(<span class="variable">data</span>);
<span class="variable">foundUser</span>.<span class="variable">set</span>({<span class="string">'hashPass'</span>: <span class="variable">calculatedHash</span>});
<span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">null</span>, <span class="variable">foundUser</span>);
});
}
<span class="keyword">else</span> {
<span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[verifyUserAccount] invalid password'</span>));
}
});
}
<span class="keyword">else</span> {
<span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[verifyUserAccount] salt not found'</span>));
}
});
}</code></pre>
</td>
</tr>
<tr class="code">
<td class="docs">
<p>Verifies that the two passwords match, then use the current timestamp to salt a hash of the password. Store it all in a user model which we will save as a poor man's profile if everything succeeds.</p>
<p>Any failure along the way means we callback with an error.</p>
<ul><li><strong>para</strong>: <em>m</em>
: {string} name</li><li><strong>para</strong>: <em>m</em>
: {string} pass1</li><li><strong>para</strong>: <em>m</em>
: {string} pass2</li><li><strong>para</strong>: <em>m</em>
: {string} email</li><li><strong>para</strong>: <em>m</em>
: {string} ponies</li><li><strong>para</strong>: <em>m</em>
: {function} fn</li><li><strong>ap</strong>: <em>i</em>
: public
</li></ul>
</td>
<td class="code">
<pre><code><span class="variable">exports</span>.<span class="variable">createNewUserAccount</span> = <span class="keyword">function</span>(<span class="variable">name</span>, <span class="variable">pass1</span>, <span class="variable">pass2</span>, <span class="variable">email</span>, <span class="variable">ponies</span>, <span class="variable">fn</span>) {
<span class="keyword">if</span> (<span class="variable">pass1</span> !== <span class="variable">pass2</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[createNewUserAccount] Passwords do not match'</span>));
<span class="keyword">var</span> <span class="variable">newUser</span> = <span class="keyword">new</span> <span class="variable">models</span>.<span class="class">User</span>({<span class="variable">name</span>: <span class="variable">name</span>, <span class="variable">email</span>: <span class="variable">email</span>, <span class="variable">ponies</span>: <span class="variable">ponies</span>});
<span class="keyword">var</span> <span class="variable">rKey</span> = <span class="string">'user:'</span> + <span class="variable">name</span>;
<span class="variable">rc</span>.<span class="variable">set</span>(<span class="variable">rKey</span>, <span class="variable">name</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>){
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[createNewUserAccount] SET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">' for value: '</span> + <span class="variable">name</span>));
<span class="keyword">var</span> <span class="variable">salt</span> = <span class="keyword">new</span> <span class="class">Date</span>().<span class="variable">getTime</span>();
<span class="variable">rc</span>.<span class="variable">set</span>(<span class="variable">rKey</span> + <span class="string">'.salt'</span>, <span class="variable">salt</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[createNewUserAccount] SET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.salt'</span> + <span class="string">' for value: '</span> + <span class="variable">salt</span>));
<span class="keyword">var</span> <span class="variable">hashPass</span> = <span class="class">Hash</span>.<span class="variable">sha512</span>(<span class="variable">salt</span> + <span class="string">'_'</span> + <span class="variable">pass1</span>);
<span class="variable">rc</span>.<span class="variable">set</span>(<span class="variable">rKey</span> + <span class="string">'.hashPass'</span>, <span class="variable">hashPass</span>, <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[createNewUserAccount] SET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.hashPass'</span> + <span class="string">' for value: '</span> + <span class="variable">hashPass</span>));
<span class="variable">rc</span>.<span class="variable">set</span>(<span class="variable">rKey</span> + <span class="string">'.profile'</span>, <span class="variable">newUser</span>.<span class="variable">xport</span>(), <span class="keyword">function</span>(<span class="variable">err</span>, <span class="variable">data</span>) {
<span class="keyword">if</span>(<span class="variable">err</span>) <span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">new</span> <span class="class">Error</span>(<span class="string">'[createNewUserAccount] SET failed for key: '</span> + <span class="variable">rKey</span> + <span class="string">'.profile'</span> + <span class="string">' for user profile'</span>));
<span class="variable">newUser</span>.<span class="variable">set</span>({<span class="string">'hashPass'</span>: <span class="variable">hashPass</span>});
<span class="keyword">return</span> <span class="variable">fn</span>(<span class="keyword">null</span>, <span class="variable">newUser</span>);
});
});
});
});
}
})()
</code></pre>
</td>
</tr><tr class="filename"><td><h2 id="models/models.js"><a href="#">models</a></h2></td><td>models/models.js</td></tr><tr class="code">
<td class="docs">
<p>(function () {
var server = false, models;
if (typeof exports !== 'undefined') {
<em> = require('underscore').</em>;
Backbone = require('backbone');</p>
<pre><code> models = exports;
server = true;
} else {
models = this.models = {};
}
//
//models
//
models.User = Backbone.Model.extend({});
models.ChatEntry = Backbone.Model.extend({});
models.ClientCountModel = Backbone.Model.extend({
defaults: {
"clients": 0
},
updateClients: function(clients){
this.set({clients: clients});
}
});
models.NodeChatModel = Backbone.Model.extend({
defaults: {
"clientId": 0
},
initialize: function() {
this.chats = new models.ChatCollection();
}
});
//
//Collections
//
models.ChatCollection = Backbone.Collection.extend({
model: models.ChatEntry
});
//
//Model exporting/importing
//
Backbone.Model.prototype.xport = function (opt) {
var result = {},
settings = _({recurse: true}).extend(opt || {});
function process(targetObj, source) {
targetObj.id = source.id || null;
targetObj.cid = source.cid || null;
targetObj.attrs = source.toJSON();
_.each(source, function (value, key) {
// since models store a reference to their collection
// we need to make sure we don't create a circular refrence
if (settings.recurse) {
if (key !== 'collection' && source[key] instanceof Backbone.Collection) {
targetObj.collections = targetObj.collections || {};
targetObj.collections[key] = {};
targetObj.collections[key].models = [];
targetObj.collections[key].id = source[key].id || null;
_.each(source[key].models, function (value, index) {
process(targetObj.collections[key].models[index] = {}, value);
});
} else if (source[key] instanceof Backbone.Model) {
targetObj.models = targetObj.models || {};
process(targetObj.models[key] = {}, value);
}
}
});
}
process(result, this);
return JSON.stringify(result);
};
Backbone.Model.prototype.mport = function (data, silent) {
function process(targetObj, data) {
targetObj.id = data.id || null;
targetObj.set(data.attrs, {silent: silent});
// loop through each collection
if (data.collections) {
_.each(data.collections, function (collection, name) {
targetObj[name].id = collection.id;
_.each(collection.models, function (modelData, index) {
var newObj = targetObj[name]._add({}, {silent: silent});
process(newObj, modelData);
});
});
}
if (data.models) {
_.each(data.models, function (modelData, name) {
process(targetObj[name], modelData);
});
}
}
process(this, JSON.parse(data));
return this;
};</code></pre>
<p>})()</p>
</td>
<td class="code">
</td>
</tr><tr class="filename"><td><h2 id="views/views.js"><a href="#">views</a></h2></td><td>views/views.js</td></tr><tr class="code">
<td class="docs">
<p>//
//Views
//</p>
<p>var ChatView = Backbone.View.extend({
tagName: 'li',</p>
<pre><code>initialize: function(options) {
_.bindAll(this, 'render');
this.model.bind('all', this.render);
},
render: function() {
$(this.el).html(this.model.get("name") + ": " + this.model.get("text"));
return this;
}</code></pre>
<p>});</p>
<p>var ClientCountView = Backbone.View.extend({
initialize: function(options) {
_.bindAll(this, 'render');
this.model.bind('all', this.render);
},</p>
<pre><code>render: function() {
this.el.html(this.model.get("clients"));
return this;
}</code></pre>
<p>});</p>
<p>var NodeChatView = Backbone.View.extend({
initialize: function(options) {
<em>.bindAll(this, 'sendMessage');
this.model.chats.bind('add', this.addChat);
this.socket = options.socket;
this.clientCountView = new ClientCountView({model: new models.ClientCountModel(), el: $('#client</em>count')});
}</p>
<pre><code>, events: {
"submit #messageForm" : "sendMessage"
}
, addChat: function(chat) {
var view = new ChatView({model: chat});
$('#chat_list').append(view.render().el);
}
, msgReceived: function(message){
switch(message.event) {
case 'initial':
this.model.mport(message.data);
break;
case 'chat':
var newChatEntry = new models.ChatEntry();
newChatEntry.mport(message.data);
this.model.chats.add(newChatEntry);
break;
case 'update':
this.clientCountView.model.updateClients(message.clients);
break;
}
}
, sendMessage: function(){
var inputField = $('input[name=message]');
var chatEntry = new models.ChatEntry({name: this.model.get('userName'), text: inputField.val()});
this.socket.send(chatEntry.xport());
inputField.val('');
}</code></pre>
<p>});</p>
</td>
<td class="code">
</td>
</tr><tr class="filename"><td><h2 id="lib/backbone.js"><a href="#">backbone</a></h2></td><td>lib/backbone.js</td></tr><tr class="code">
<td class="docs">
<p>// Backbone.js 0.3.3
// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://documentcloud.github.com/backbone</p>
<p>(function(){</p>
<p> // Initial Setup
// -------------</p>
<p> // The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = this.Backbone = {};
}</p>
<p> // Current version of the library. Keep in sync with <code>package.json</code>.
Backbone.VERSION = '0.3.3';</p>
<p> // Require Underscore, if we're on the server, and it's not already present.
var <em> = this.</em>;
if (!<em> && (typeof require !== 'undefined')) </em> = require('underscore')._;</p>
<p> // For Backbone's purposes, either jQuery or Zepto owns the <code>$</code> variable.
var $ = this.jQuery || this.Zepto;</p>
<p> // Turn on <code>emulateHTTP</code> to use support legacy HTTP servers. Setting this option will
// fake <code>"PUT"</code> and <code>"DELETE"</code> requests via the <code>_method</code> parameter and set a
// <code>X-Http-Method-Override</code> header.
Backbone.emulateHTTP = false;</p>
<p> // Turn on <code>emulateJSON</code> to support legacy servers that can't deal with direct
// <code>application/json</code> requests ... will encode the body as
// <code>application/x-www-form-urlencoded</code> instead and will send the model in a
// form param named <code>model</code>.
Backbone.emulateJSON = false;</p>
<p> // Backbone.Events
// -----------------</p>
<p> // A module that can be mixed in to <em>any object</em> in order to provide it with
// custom events. You may <code>bind</code> or <code>unbind</code> a callback function to an event;
// <code>trigger</code>-ing an event fires all callbacks in succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.bind('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
Backbone.Events = {</p>
<pre><code>// Bind an event, specified by a string name, `ev`, to a `callback` function.
// Passing `"all"` will bind the callback to all events fired.
bind : function(ev, callback) {
var calls = this._callbacks || (this._callbacks = {});
var list = this._callbacks[ev] || (this._callbacks[ev] = []);
list.push(callback);
return this;
},
// Remove one or many callbacks. If `callback` is null, removes all
// callbacks for the event. If `ev` is null, removes all bound callbacks
// for all events.
unbind : function(ev, callback) {
var calls;
if (!ev) {
this._callbacks = {};
} else if (calls = this._callbacks) {
if (!callback) {
calls[ev] = [];
} else {
var list = calls[ev];
if (!list) return this;
for (var i = 0, l = list.length; i < l; i++) {
if (callback === list[i]) {
list.splice(i, 1);
break;
}
}
}
}
return this;
},
// Trigger an event, firing all bound callbacks. Callbacks are passed the
// same arguments as `trigger` is, apart from the event name.
// Listening for `"all"` passes the true event name as the first argument.
trigger : function(ev) {
var list, calls, i, l;
if (!(calls = this._callbacks)) return this;
if (calls[ev]) {
list = calls[ev].slice(0);
for (i = 0, l = list.length; i < l; i++) {
list[i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
if (calls['all']) {
list = calls['all'].slice(0);
for (i = 0, l = list.length; i < l; i++) {
list[i].apply(this, arguments);
}
}
return this;
}</code></pre>
<p> };</p>
<p> // Backbone.Model
// --------------</p>
<p> // Create a new model, with defined attributes. A client id (<code>cid</code>)
// is automatically generated and assigned for you.
Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (defaults = this.defaults) {
if (<em>.isFunction(defaults)) defaults = defaults();
attributes = </em>.extend({}, defaults, attributes);
}
this.attributes = {};
this.<em>escapedAttributes = {};
this.cid = </em>.uniqueId('c');
this.set(attributes, {silent : true});
this.<em>changed = false;
this.</em>previousAttributes = _.clone(this.attributes);
if (options && options.collection) this.collection = options.collection;
this.initialize(attributes, options);
};</p>
<p> // Attach all inheritable methods to the Model prototype.
_.extend(Backbone.Model.prototype, Backbone.Events, {</p>
<pre><code>// A snapshot of the model's previous attributes, taken immediately
// after the last `"change"` event was fired.
_previousAttributes : null,
// Has the item been changed since the last `"change"` event?
_changed : false,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute : 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
// Return a copy of the model's `attributes` object.
toJSON : function() {
return _.clone(this.attributes);
},
// Get the value of an attribute.
get : function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape : function(attr) {