-
Notifications
You must be signed in to change notification settings - Fork 0
/
duality.js
841 lines (756 loc) · 27.8 KB
/
duality.js
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
/**
* Duality Web Server
* Copyright (c) 2012 Kristoffer Andersen, stoffera <a>. gmail.com
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* This is a simple node.js HTTP server.
* It can only serve content in twp ways, hence the name duality.
* 1. It can serve static files from a root dir, just as any other conventional server.
* 2. It can map URL's to specific functions and pass specific arguments.
* These two ways of serving content is very powerful. Serve your HTML, JS, CSS
* etc through method no. 1. When use method no. 2 to provide you WebApp with
* specific data.
*/
/**
* Libraries used by the duality server
* @private
* @type {Object}
*/
var d = {
http: require('http'),
fs: require('fs'),
url: require('url'),
path: require('path'),
crypt: require('crypto')
};
/**
* Initialize and return a new duality server object
* This can not be called directly. From you application
* use the createServer() function.
*
* @constructor
* @param {string} serve_directory the path to the folder where the static files are shared from
* @param {Object=} opt_routes_table A dictionary of regex string and corrosponding functions.
* @param {Object=} opt_options a dictionary of extra options to the server
* @author Kristoffer Andersen
*/
var duality = function(serve_directory, opt_routes_table, opt_options) {
this.serveDirectory = d.path.resolve(__dirname,serve_directory);
//Assign empty routing table or the provided one
this.routes = !opt_routes_table ? {} : opt_routes_table;
//Parse the routes to include method options
for (var r in this.routes) {
//should we parse it to extended format?
if (typeof(this.routes[r]) == 'function') {
this.routes[r] = {func:this.routes[r], method:'any'};
}
else if (typeof(this.routes[r]) == 'object') {
if (!(this.routes[r]['func'] && this.routes[r]['method'])) {
throw("Malformed route object. Must be: {func: function, method: string}");
}
}
else {
throw("Malformed route object. Must be: {func: function, method: string}");
}
}
//Assign any options provided
if (opt_options) {
this.routesIgnoreQueryString = opt_options['routesIgnoreQueryString'] != undefined ? opt_options['routesIgnoreQueryString'] : this.routesIgnoreQueryString;
this.serverPort = opt_options['serverPort'] || this.serverPort;
this.useSessions = opt_options['useSessions']!=undefined ? opt_options['useSessions'] : this.useSessions;
this.sessionIdentifier = opt_options['sessionIdentifier'] || this.sessionIdentifier;
this.serverString = opt_options['serverString'] || this.serverString;
this.useAccessLog = opt_options['useAccessLog'] != undefined ? opt_options['useAccessLog'] : this.useAccessLog;
this.useAccessControl = opt_options['useAccessControl'] || this.useAccessControl;
this.accessLoginUrl = opt_options['accessLoginUrl'] || this.accessLoginUrl;
this.accessResourceCallback = opt_options['accessResourceCallback'] || this.accessResourceCallback;
this.httpAuthRealm = opt_options['httpAuthRealm'] || this.httpAuthRealm;
this.httpAuthUserLookupCallback = opt_options['httpAuthUserLookupCallback'] || this.httpAuthUserLookupCallback;
this.httpAuthLoginSuccessCallback = opt_options['httpAuthLoginSuccessCallback'] || this.httpAuthLoginSuccessCallback;
this.httpAuthLoginFailedCallback = opt_options['httpAuthLoginFailedCallback'] || this.httpAuthLoginFailedCallback;
}
//Initialize a sessions array
this.sessions = {};
//Setup a closure to preserve context of callback
var context = this;
this.http = d.http.createServer( function(req,res){context.incomeRequest.call(context,req,res);} );
this.http.listen(this.serverPort);
console.log(this.serverString+" server listening on port "+this.serverPort+"...");
};
/**
* The list of routes, that mappes URLs to functions.
* @protected
* @type {Object}
*/
duality.prototype.routes = null;
/**
* The path to the servers root serving directory
* @protected
* @type {string}
*/
duality.prototype.serveDirectory = "";
/**
* Server listening port (normally 80)
* @protected
* @type {number}
*/
duality.prototype.serverPort = 8080;
/**
* Set this to true to keep set a session cookie for every client
* @public
* @type {boolean}
*/
duality.prototype.useSessions = true;
/**
* Set this to true to strip query strings in incomming URLs from the
* route matching. This means routes depending on the existence of query
* strings will never be matched.
* If active you can still access the query string content from inside your
* route functions by using the http.ServerRequest object.
* This ignore function is useful is you need to catch JSONP callbacks in the request.
*
* @public
* @type {boolean}
*/
duality.prototype.routesIgnoreQueryString = false;
/**
* Name identifier of the cookie string that holds the session
* @protected
* @type {string}
*/
duality.prototype.sessionIdentifier = "duality-session";
/**
* Server identification string header
* @protected
* @type {string}
*/
duality.prototype.serverString = "duality";
/**
* Turn on / off the access log to stdout
* @public
* @type {boolean}
*/
duality.prototype.useAccessLog = true;
/**
* Turn on / off the access control system
* @public
* @type {boolean}
*/
duality.prototype.useAccessControl = false;
/**
* URL to a login page or a function to display the login page.
* If NULL and access control system is activated - HTTP Auth is used.
* @public
* @type {?string}
*/
duality.prototype.accessLoginUrl = null;
/**
* Resource access control callback function
* If the access control system is activated, on every incoming
* request, this function will be called. This function should return TRUE
* if it is allowed to access the URL. FALSE otherwise. The callback function
* is passed a session object, unique for the current client.
* If the callback is NULL, the access control system is effectually OFF.
* @public
* @type {?function(Object):boolean}
*/
duality.prototype.accessResourceCallback = null;
/**
* Accociative array of current sessions
* @protected
* These will never timeout.
*/
duality.prototype.sessions = null;
/**
* The standard node http server
* @protected
* @type {http.createServer}
*/
duality.prototype.http = null;
/**
* The http authetication realm. This will be hashed along with password and usernames.
* Any user table relying on hashed passwords, should retain a fixed realm.
* @protected
* @type {string}
*/
duality.prototype.httpAuthRealm = "Login";
/**
* Callback function you must define to check the HTTP Auth login credentials.
* The function gets passed the username, and must check the users table for that entry.
* If the entry exists, the function must return the HTTP Auth login hash, as returned
* by this.httpAuthHash();
* @public
* @type {function(string):?string}
*/
duality.prototype.httpAuthUserLookupCallback = null;
/**
* Callback to tell a HTTP Auth login succeeded.
* @public
* @type {function(string)}
*/
duality.prototype.httpAuthLoginSuccessCallback = null;
/**
* Callback to tell a HTTP Auth login failed
* @public
* @type {function(string)}
*/
duality.prototype.httpAuthLoginFailedCallback = null;
/**
* The handles every new incoming request to the server
* @protected
* @param {http.Request} req A incoming HTTP request
* @param {http.Response} res The HTTP response for the current request
*/
duality.prototype.incomeRequest = function(req, res) {
var url = d.url.parse(req.url, true);
//Set the server header
res.setHeader('Server',this.serverString);
//create a session if activated
if (this.useSessions) this.initSession(req,res);
//log the access
if (this.useAccessLog) this.logRequest(req);
//check access if system is activated
if (this.useSessions && this.useAccessControl && this.accessResourceCallback) {
if (!this.checkLogin(req,res)) {
//client not logged in
//redirect or present http auth screen
if (this.accessLoginUrl == null) {
//Present HTTP Auth
var nonce = req.currentSession.id;
var opaque = req.currentSession.id+"abcdef";
res.setHeader("WWW-Authenticate","Digest realm=\"Login\",qop=\"auth,auth-int\",nonce=\""+nonce+"\",opaque=\""+opaque+"\"");
this.accessDenied(req, res);
return;
}
else {
//Redirect to login url
res.writeHead(302,{'Location': this.accessLoginUrl});
res.end();
return;
}
}
//User is logged in if we get here
}
//Try to match a route from the URL
var matchURL;
if (this.routesIgnoreQueryString) {
matchURL = d.url.parse(req.url);
matchURL = matchURL.pathname;
}
else {
matchURL = req.url;
}
var matched = false;
for (var route in this.routes) {
var match = matchURL.match(route);
if (match != null) {
if (this.routes[route].method.toLowerCase() == req.method.toLowerCase()
|| this.routes[route].method.toLowerCase() == "any"
|| this.routes[route].method.toLowerCase() == "all")
{
this.routes[route].func.call(this, match, req, res);
matched = true;
break;
}
}
}
//No route matched, look for file on disk to serve
if (!matched)
this.staticServe(url,req,res);
};
/**
* Try to find a file matching the URL and serve it. If the file is not found give 404 error.
* URL to "/" will be rewritten to "/index.htm".
* @public
* @param {string} url The URL for the request
* @param {http.request} req the current http request
* @param {http.response} res the response for the current http request
*/
duality.prototype.staticServe = function(url, req, res) {
if (url.pathname == '/')
url.pathname = 'index.htm';
var self = this;
d.fs.exists(d.path.join(this.serveDirectory,url.pathname),function(exists){
if (!exists) {
self.notFound(req, res);
return;
}
else {
self.serveFile(d.path.join(self.serveDirectory,url.pathname), req , res);
}
});
};
/**
* Check if the user is logged in. And has access to the requested resource
* @protected
* @param {http.request} req the current http request
* @param {http.response} res the response for the current http request
*/
duality.prototype.checkLogin = function(req, res) {
//Ask the resource access callback if the current user has access
var access = this.accessResourceCallback(req.currentSession, req, res);
if (access) {
return true;
}
//Access was denied, check for any HTTP Auth header
else if (this.accessLoginUrl == null && req.headers['authorization']) {
if (req.headers['authorization'].indexOf('Digest') != -1) {
var digest = this.parseDigest(req,res);
console.log("Querying user: "+digest.username);
var hash = null;
if (this.httpAuthUserLookupCallback) hash = this.httpAuthUserLookupCallback(digest.username, req, res);
else {
console.error("Cannot authenticate HTTP Auth login, no callback function defined.\nDefine callback for: httpAuthUserLookupCallback");
return false;
}
if (hash == null) {
console.log("No such user: "+digest.username);
if (this.httpAuthLoginFailedCallback) this.httpAuthLoginFailedCallback(digest.username, req, res);
return false;
}
// var ha1 = n.crypt.createHash('md5');
// ha1.update(digest.username+":"+this.httpAuthRealm+":"+users[digest.username]['pass']);
var ha2 = d.crypt.createHash('md5');
ha2.update(req.method+":"+digest.uri);
var resp = d.crypt.createHash('md5');
resp.update(hash+":"+digest.nonce+":"+digest.nc+":"+digest.cnonce+":"+digest.qop+":"+ha2.digest('hex'));
var servResp = resp.digest('hex');
if (servResp == digest.response){
console.log("LOGIN SUCCESS: "+digest.username);
if (this.httpAuthLoginSuccessCallback) this.httpAuthLoginSuccessCallback(digest.username, req, res);
return true;
}
else {
console.log("LOGIN: wrong credentials!");
if (this.httpAuthLoginFailedCallback) this.httpAuthLoginFailedCallback(digest.username, req, res);
return false;
}
}
else if (req.headers['authorization'].indexOf('Basic') != -1)
console.log("no basic auth support!");
else
console.log("auth method not supported!");
}
return false;
};
/**
* Adds an entry to the routes table, serving only
* GET requests. If an existing route matching to one you try to add
* it will be overwritten.
*
* @param {string} regexString Doubled escape route regex
* @param {function(Object, http.ServerRequest, http.ServerResponse)} func
* @public
*/
duality.prototype.get = function(regexString, func) {
this.routes[regexString] = {
func: func,
method: 'get'
};
};
/**
* Adds an entry to the routes table, serving only
* POST requests. If an existing route matching to one you try to add
* it will be overwritten.
* A fourth parameter is passed to the callback function. This is the contains of any
* existing POST form data.
*
* @param {string} regexString Doubled escape route regex
* @param {function(Object,http.ServerRequest,http.ServerResponse)} func
* @public
*/
duality.prototype.post = function(regexString, func) {
this.routes[regexString] = {
func: func,
method: 'post'
};
};
/**
* Adds an entry to the routes table, serving any
* requests type. If an existing route matching to one you try to add
* it will be overwritten.
*
* @param {string} regexString Doubled escape route regex
* @param {function(Object, http.ServerRequest, http.ServerResponse)} func
* @public
*/
duality.prototype.any = function(regexString, func) {
this.routes[regexString] = {
func: func,
method: 'any'
};
};
/**
* Adds an entry to the routes table, serving only
* PUT requests. If an existing route matching to one you try to add
* it will be overwritten.
*
* @param {string} regexString Doubled escape route regex
* @param {function(Object, http.ServerRequest, http.ServerResponse)} func
* @public
*/
duality.prototype.put = function(regexString, func) {
this.routes[regexString] = {
func: func,
method: 'put'
};
};
/**
* Detects if the request is a JSONP request. This means it has a callback function
* defnied in its query string. This method only tells you JSONP is requested, it
* does not encapsulate your response in a JS function for you. You must do
* that yourself. The default callback function name is "callabck".
*
* @param {http.ServerRequest} req the incomming request to check
* @param {string=} opt_callbackName Provide a custom name of the callback function
* @return {boolean|string} the callback value if the request contains a JSONP callback, false otherwise
*/
duality.prototype.detectJsonp = function(req, opt_callbackName) {
if (!opt_callbackName) opt_callbackName = "callback";
var u = d.url.parse(req.url, true);
return (!u.query[opt_callbackName]) ? false : u.query[opt_callbackName];
};
/**
* Emit a 404 error to the client and terminate the request.
* If request has json as accepted content type, this is ackownledged.
*
* @param {http.ServerRequest} req The servers request object
* @param {http.ServerResponse} res The servers response object
* @param {string=} opt_custom_msg Optional message to replace the std error 404
* @param {string=} opt_std_err_msg Optional message to print to std. err.
*/
duality.prototype.notFound = function(req, res, opt_custom_msg, opt_std_err_msg) {
opt_custom_msg = opt_custom_msg ? opt_custom_msg : "The resource you were looking for was not found on the server.";
if (opt_std_err_msg) console.error(opt_std_err_msg);
if (req.headers['accept'] == 'application/json' || req.headers['content-type'] == 'application/json') {
res.writeHead(404,{'Content-Type':'application/json'});
res.end(JSON.stringify({'error':'404','msg':opt_custom_msg}));
}
else {
res.writeHead(404,{'Content-Type':'text/html'});
res.end("<h1>Not Found</h1><p>"+opt_custom_msg+"</p>");
}
};
/**
* Emit an access denied error to the client. Either in html or JSON.
* This should be used when authorization is needed.
* will terminate the request.
*
* @public
* @param {http.ServerRequest} req The server request object
* @param {http.ServerResponse} res The server response object
* @param {string=} opt_custom_msg A custom error text
* @param {string=} opt_std_err An optional text to emit ot std. err.
*/
duality.prototype.accessDenied = function(req, res, opt_custom_msg, opt_std_err){
opt_custom_msg = opt_custom_msg ? opt_custom_msg : "You are not authorized to access the requested resource.";
if (opt_std_err) console.error(opt_std_err);
if (req.headers['accept'] == 'application/json' || req.headers['content-type'] == 'application/json') {
res.writeHead(401,{'Content-Type':'application/json'});
res.end(JSON.stringify({'error':'401','msg':opt_custom_msg}));
}
else {
res.writeHead(401,{'Content-Type':'text/html'});
res.end("<h1>Not Authorized</h1><p>"+opt_custom_msg+"</p>");
}
};
/**
* Emit a forbidden error to the client. Either in html or JSON.
* This should be used when is not allowed to access a resource and never will
* be. Will terminate the request.
*
* @public
* @param {http.ServerRequest} req The server request object
* @param {http.ServerResponse} res The server response object
* @param {string=} opt_custom_msg A custom error text
* @param {string=} opt_std_err An optional text to emit ot std. err.
*/
duality.prototype.forbidden = function(req, res, opt_custom_msg, opt_std_err){
opt_custom_msg = opt_custom_msg ? opt_custom_msg : "You are not allowed to access the requested resource.";
if (opt_std_err) console.error(opt_std_err);
if (req.headers['accept'] == 'application/json' || req.headers['content-type'] == 'application/json') {
res.writeHead(403,{'Content-Type':'application/json'});
res.end(JSON.stringify({'error':'403','msg':opt_custom_msg}));
}
else {
res.writeHead(403,{'Content-Type':'text/html'});
res.end("<h1>Forbidden Resource</h1><p>"+opt_custom_msg+"</p>");
}
};
/**
* Emit a bad request error to the client. Either in html or JSON.
* This should be used when the client has used a malformed request
* and wrong input or syntax. Will terminate the request.
*
* @public
* @param {http.ServerRequest} req The server request object
* @param {http.ServerResponse} res The server response object
* @param {string=} opt_custom_msg A custom error text
* @param {string=} opt_std_err An optional text to emit ot std. err.
*/
duality.prototype.badRequest = function(req, res, opt_custom_msg, opt_std_err){
opt_custom_msg = opt_custom_msg ? opt_custom_msg : "The request parameters was malformed and could not be understood.";
if (opt_std_err) console.error(opt_std_err);
if (req.headers['accept'] == 'application/json' || req.headers['content-type'] == 'application/json') {
res.writeHead(400,{'Content-Type':'application/json'});
res.end(JSON.stringify({'error':'400','msg':opt_custom_msg}));
}
else {
res.writeHead(400,{'Content-Type':'text/html'});
res.end("<h1>Bad Request</h1><p>"+opt_custom_msg+"</p>");
}
};
/**
* Create a HASH to use with the HTTP AUth for this server. A list of allowed users for
* this server, can store the hashed value, instead of the passwords in clear text.
* @public
* @param {string} username The username is part of the hash in HTTP Auth Digest
* @param {string} password The password in clear text
* @return {string} The hashed value as a HEX string
*/
duality.prototype.httpAuthHash = function(username, password) {
return exports.getHttpAuthUserDigest(username, this.httpAuthRealm, password);
};
/**
* Parse the content of the HTTP Auth digest header
* @protected
* @param {http.request} req the current http request
* @param {http.response} res the response for the current http request
*/
duality.prototype.parseDigest = function(req, res) {
if (req.headers['authorization'] == undefined) {
console.error("parseDigest - no digest header present!",req.headers);
return null;
}
var dAr = req.headers['authorization'].substring(7).replace(/ /g,"").split(",");
var digest = {};
for (var i=0;i<dAr.length;i++) {
var match = dAr[i].match(/(\w+)=(".+"|[\d\w]+)/);
digest[match[1]] = match[2].replace(/"/g,"");
}
return digest;
};
/**
* Log the request params to stdout
* @protected
* @param {http.request} req the current http request
*/
duality.prototype.logRequest = function(req) {
var d = new Date();
var log = d.toUTCString()+", "+req.method+", "+req.url+", "+req.connection.remoteAddress+", "+req.headers['user-agent'];
if (req.currentSession && req.currentSession.login)
log = log + ", "+req.currentSession.login;
console.log(log+";");
};
/**
* Setup a new session for the request or attach it to an existing session
* @protected
* @param {http.request} req the current http request
* @param {http.response} res the response for the current http request
*/
duality.prototype.initSession = function(req, res) {
//look for existing session in cookies
if (req.headers['cookie'] != undefined) {
var c_array = req.headers['cookie'].split('; ');
var cookies = {};
for (var i=0; i<c_array.length; i++) {
var c = c_array[i].split('=');
cookies[c[0]] = c[1];
}
if (cookies[this.sessionIdentifier] != undefined && this.sessions[cookies[this.sessionIdentifier]] != undefined) {
req.currentSession = this.sessions[cookies[this.sessionIdentifier]];
return;
}
}
//look for exiting session as GET parameter
var url = d.url.parse(req.url, true);
if (url.query && url.query[this.sessionIdentifier] && this.sessions[url.query[this.sessionIdentifier]] != undefined) {
req.currentSession = this.sessions[url.query[this.sessionIdentifier]];
return;
}
//setup a new session
var newSesUID = Math.random().toString().substring(2);
res.setHeader('Set-Cookie',this.sessionIdentifier+'='+newSesUID);
this.sessions[newSesUID] = {'id':newSesUID, 'cnt':1};
req.currentSession = this.sessions[newSesUID];
};
/**
* Serve the content of any file on the disk.
* This method is used by the internal static files serving. You can also call this function from you own code
* to serve any file you like.
* Partial content ranges are supported, so only part of the file is served, if request by the client.
* @public
* @param {string} filePath path to the file that should be served
* @param {http.request} req the current http request
* @param {http.response} res the response for the current http request
* @param {boolean} opt_dont_detect_content_type Set this to true to avoid auto detection and setting of content-type header
* @param {boolean=} opt_attachment Set this to TRUE to tell the browser to serve the file as a download
*/
duality.prototype.serveFile = function(filePath, req, res, opt_dont_detect_content_type, opt_attachment) {
if (!opt_attachment) opt_attachment = false;
//Get the file details
d.fs.stat(filePath, function(err,stat){
//abort if error
if (err) {
console.error("Could not get file stat: "+err);
res.writeHead(500,{'Content-Type':'text/html'});
res.end("<h1>Internal server error</h1><p>An error occurred while server the content</p>");
return;
}
//Async we have file details, setup response headers
var start = 0;
var partial = false;
var end = parseInt(stat.size,10)==0?0:parseInt(stat.size,10)-1;
var fileType = d.path.extname(filePath).substr(1);
//Setup header
var header = {
'Cache-Control': 'public',
Connection: 'keep-alive',
'Last-Modified': stat.mtime,
'Content-Disposition': (opt_attachment?'attachment':'inline')+'; filename='+d.path.basename(filePath)
};
//only set content type if required
if (!opt_dont_detect_content_type) {
header['Content-Type'] = (exports.mimeTypes[fileType] != undefined ? exports.mimeTypes[fileType] : 'application/octet-stream');
}
//Http Cache control
var etag = stat.size + "-" + Date.parse(stat.mtime);
if (req.headers['if-none-match'] === etag) {
res.writeHead(304,header);
res.end();
return;
}
else {
header['ETag'] = etag;
}
if (req.headers['range']) {
var match = req.headers.range.match(/bytes=(\d+)-(\d*)/);
partial = true;
start = parseInt(match[1],10);
if (match[2] != undefined && match[2] != '')
end = parseInt(match[2],10);
}
var length = (end == 0 && start == 0) ? 0 : (end - start + 1);
var stream = d.fs.createReadStream(filePath,{
flags: 'r',
encoding: null,
fd: null,
start: start,
end: end,
bufferSize:64*1064
});
if (stream) {
if (partial) {
header.Status = "206 Partial Content";
header['Accept-Ranges'] = 'bytes';
header['Content-Range'] = 'bytes '+start+"-"+end+"/"+stat.size;
}
header.Pragma = 'public';
header['Content-Transfer-Encoding'] = 'binary';
header['Content-Length'] = length;
res.writeHead((start==0?200:206),header);
stream.pipe(res);
//make sure to clean up file resource on response end
res.on('close', function(){
stream.destroy();
});
}
});
};
/**
* List of supported MIME types. Any file extension not present here
* will be served as application/octet-stream.
* If you need additional MIME types, just append to this object or
* overwrite it. Any changes to this will immediately effect all server instances.
* @type {Object}
*/
exports.mimeTypes = {
'htm' : 'text/html',
'html' : 'text/html',
'txt' : 'text/plain',
'css' : 'text/css',
'xml' : 'text/xml',
'csv' : 'text/csv',
'js' : 'application/x-javascript',
'json' : 'application/x-javascript',
'pdf' : 'application/pdf',
'zip' : 'application/zip',
'gz' : 'application/gzip',
'tgz' : 'application/gzip',
'gzip' : 'application/gzip',
'tar' : 'application/x-tar',
'exe' : 'application/octet-stream',
'img' : 'application/octet-stream',
'bin' : 'application/octet-stream',
'swf' : 'application/x-shockwave-flash',
'mpg' : 'video/mpeg',
'mpeg' : 'video/mpeg',
'mov' : 'video/quicktime',
'm4v' : 'video/mp4',
'mp4' : 'video/mp4',
'webm' : 'video/webm',
'mkv' : 'video/x-matroska',
'avi' : 'video/x-msvideo',
'flv' : 'video/x-flv',
'm4a' : 'audio/mp4',
'mp3' : 'audio/mpeg',
'ogg' : 'audio/ogg',
'wav' : 'audio/wav',
'mid' : 'audio/midi',
'png' : 'image/png',
'gif' : 'image/gif',
'jpg' : 'image/jpeg',
'jpeg' : 'image/jpeg',
'ico' : 'image/x-icon',
'svg' : 'image/svg+xml',
'tiff' : 'image/tiff'
};
/**
* Create a new duality server object instance. This function returns
* a server object serving the provided directory and calling functions defined in the routes table.
* If you just want a static file server, then omit the routes table patameter.
* The server takes an options object. You can set additional server
* parameters through this object.
*
* @param {string} serve_directory the path to the folder where the static files are shared from
* @param {Object=} opt_routes_table A dictionary of regex string and corrosponding functions.
* @param {Object=} opt_options a dictionary of extra options to the server
* @return {duality} An instance of the duality server class.
*/
exports.createServer = function(serve_directory, opt_routes_table, opt_options) {
return new duality(serve_directory, opt_routes_table, opt_options);
};
/**
* Global function to create the HTTP Auth Digest HASH of Username:Realm:password
* if you know what Realm to use, then this function can be used to create hashes
* to store in a user table. This will eliminate the need to store the password in clear text.
* @param {string} username The username, which is a part of the hash
* @param {string} realm The realm used for the HTTP Auth
* @param {string} password the password in clear text
* @return {string} The hashed value as a HEX string
*/
exports.getHttpAuthUserDigest = function(username, realm, password) {
var ha1 = d.crypt.createHash('md5');
ha1.update(username+":"+realm+":"+password);
return ha1.digest('hex');
};
/**
* The vurrent release of Duality
* @type {number}
*/
exports.VERSION = 0.9;