forked from bipio-server/bip-pod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·2113 lines (1771 loc) · 54.2 KB
/
index.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
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
/**
*
* The Bipio Pod Bridge. Provides basic system resources, auth helpers,
* setup, invoke and data sources for actions within the pod.
*
* @author Michael Pearson <[email protected]>
* Copyright (c) 2010-2013 Michael Pearson https://github.com/mjpearson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* A Bipio Commercial OEM License may be obtained via [email protected]
*/
var cron = require('cron'),
crypto = require('crypto'),
dns = require('dns'),
extend = require('extend');
fs = require('fs'),
ipaddr = require('ipaddr.js'),
JSONPath = require('JSONPath'),
mime = require('mime'),
moment = require('moment'),
passport = require('passport'),
request = require('request'),
tldtools = require('tldtools'),
_ = require('underscore'),
util = require('util'),
uuid = require('node-uuid'),
validator = require('validator');
// utility resources
var helper = {
isObject : function(obj) {
return Object.prototype.toString.call(obj) == "[object Object]";
},
toUTC: function(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
},
now: function() {
return new Date();
},
nowUTC: function() {
return helper.toUTC(this.now());
},
nowUTCMS: function() {
return helper.nowUTC().getTime();
},
nowUTCSeconds: function() {
return helper.nowUTCMS() / 1000;
},
// Returns all ipv4/6 A records for a host
resolveHost : function(host, next) {
var tokens = tldtools.extract(host),
resolvingHost;
if (ipaddr.IPv4.isValid(host) || ipaddr.IPv6.isValid(host) ) {
next(false, [ host ], host);
} else {
resolvingHost = tokens.inspect.getDomain() || tokens.domain;
dns.resolve(resolvingHost, function(err, aRecords) {
next(err, aRecords, resolvingHost );
});
}
},
JSONPath : function(obj, path) {
return JSONPath.eval(obj, path);
},
getObject : function(input) {
if (!helper.isObject(input)) {
input = JSON.parse(input);
}
return input;
},
isObject: function(src) {
return (helper.getType(src) == '[object Object]');
},
isArray: function(src) {
return (helper.getType(src) == '[object Array]');
},
isString : function(src) {
return (helper.getType(src) == '[object String]');
},
isFunction : function(src) {
return (helper.getType(src) == '[object Function]');
},
getType: function(src) {
return Object.prototype.toString.call( src );
},
isTruthy : function(input) {
return (true === input || /1|yes|y|true/g.test(input));
},
isFalsy : function(input) {
return (false === input || /0|no|n|false/g.test(input));
},
sanitize : function(str) {
return validator.sanitize(str);
},
scrub: function(str, noEscape) {
var retStr = helper.sanitize(str).xss();
retStr = helper.sanitize(retStr).trim();
return retStr;
},
/**
* Cleans an object thoroughly. Script scrubbed, html encoded.
*/
pasteurize: function(src, noEscape) {
var attrLen, newKey;
if (helper.isArray(src)) {
var attrLen = src.length;
for (var i = 0; i < attrLen; i++) {
src[i] = helper.pasteurize(src[i], noEscape);
}
} else if (this.isString(src)) {
src = helper.scrub(src, noEscape);
} else if (helper.isObject(src)) {
var newSrc = {};
for (key in src) {
newKey = helper.scrub(key);
newSrc[newKey] = helper.pasteurize(src[key], noEscape);
}
src = newSrc;
}
return src;
},
naturalize : function(src) {
var attrLen, newKey;
if (helper.isArray(src)) {
var attrLen = src.length;
for (var i = 0; i < attrLen; i++) {
src[i] = helper.naturalize(src[i]);
}
} else if (helper.isString(src)) {
src = validator.sanitize(src).entityDecode();
} else if (helper.isObject(src)) {
var newSrc = {};
for (key in src) {
newKey = validator.sanitize(key).entityDecode();
newSrc[newKey] = helper.naturalize(src[key]);
}
src = newSrc;
}
return src;
},
strHash : function(str) {
return crypto.createHash('md5').update(str.toLowerCase()).digest("hex");
},
// Stream helpers
streamToHash : function(readStream, next) {
var hash = crypto.createHash('sha1');
hash.setEncoding('hex');
readStream.on('end', function() {
hash.end();
next(false, hash.read());
});
readStream.on('error', function(err) {
next(err);
});
readStream.pipe(hash);
},
streamToBuffer : function(readStream, next) {
var buffers = [];
readStream.on('data', function(chunk) {
buffers.push(chunk);
});
readStream.on('error', function(err) {
next(err);
});
readStream.on('end', function() {
next(false, Buffer.concat(buffers));
});
}
}
// pod required fields
var requiredMeta = [
'name',
'title',
'description'
];
// constructor
function Pod(metadata, init) {
metadata = metadata || {};
// oauth provider token refresh method
// @todo deprecate for an implementation of oAuthRefresh in pod
if (metadata.oAuthRefresh) {
this._oAuthRefresh = metadata.oAuthRefresh;
}
// post-constructor
this._podInit = init;
// Bip Pod Manifest
this._bpm = {};
// pod resources bridge
this.$resource = {};
// DAO
this._dao = null;
// logger
this._logger = null;
// action prototypes
this._actionProtos = [];
// action instances
this.actions = {};
// crons
this.crons = {};
// options
this.options = {
baseURL : '',
blacklist : [],
timezone : 'UTC',
cdnPublicBaseURL : '',
emitterBaseURL : '',
cdnBasePath : '',
config : {}
};
this._oAuthRegistered = false;
}
Pod.prototype = {
getPodBase : function(podName, literal) {
return __dirname + (literal ? '/' : '/../bip-pod-') + podName;
},
/**
* make system resources available to the pod. Invoked by the Pod registrar
* in the Channels model when bootstrapping.
*
* @param dao {Object} DAO.
* @param config {Object} Pod Config
* @param options {Object} system options
*
*/
init : function(podName, dao, cdn, logger, options) {
var reqBase = this.getPodBase(podName, options.reqLiteral),
self = this;
this.setSchema(require(reqBase + '/manifest.json'));
// check required meta's
for (var i = 0; i < requiredMeta.length; i++) {
if (!this.getBPMAttr(requiredMeta[i])) {
throw new Error(podName + ' Pod is missing required "' + requiredMeta[i] + '" metadata');
}
}
var dataSources = this.getDataSources(),
self = this,
dataSource,
model;
// set stored config
if (options.config) {
this.setConfig(options.config);
}
// merge options
_.each(options, function(value, key) {
if ('config' !== key) {
self.options[key] = value;
}
});
if (dao) {
this._dao = dao;
}
if (logger) {
this._logger = logger;
}
if (cdn) {
this.cdn = cdn;
}
if (this._dao) {
// register generic tracker
var tracker = require('./models/channel_pod_tracking');
this._dao.registerModel(tracker);
// create pod tracking container for duplicate entities
if (this.getTrackDuplicates()) {
var podDupTracker = _.clone(require('./models/dup'));
podDupTracker.entityName = this.getDataSourceName(podDupTracker.entityName);
this._dao.registerModel(podDupTracker);
}
// create pod tracking container for duplicate entities
if (this.getTrackDeltas()) {
var podDeltaTracker = _.clone(require('./models/delta'));
podDeltaTracker.entityName = this.getDataSourceName(podDeltaTracker.entityName);
this._dao.registerModel(podDeltaTracker);
}
// register pod data sources
for (var dsName in dataSources) {
if (dataSources.hasOwnProperty(dsName)) {
dataSource = _.clone(dataSources[dsName]);
// namespace the model + create an internal representation
dataSource.entityName = this.getDataSourceName(dsName);
dataSource.entitySchema = dataSource.properties;
dataSource.compoundKeyConstraints = _.object(
_.map(
dataSource.keys,
function(x) {
return [x, 1]
}
)
);
this._dao.registerModel(dataSource);
}
}
}
// register the oauth strategy
if ((this.getAuthType() === 'oauth') && (options.config && options.config.oauth)) {
var auth = self.getAuth(),
pProvider = (auth.passport && auth.passport.provider)
? auth.passport.provider
: this.getName(),
pStrategy = (auth.passport && auth.passport.strategy)
? auth.passport.strategy
: 'Strategy',
passport = require(reqBase + '/node_modules/passport-' + pProvider);
this._oAuthRegisterStrategy(
passport[pStrategy],
self.getConfig().oauth
);
// cleanup
delete auth.passport;
}
// bind pod renderers
var rpcs = this.getRPCs();
_.each(rpcs, function(rpc, key) {
rpc._href = self.options.baseUrl + '/rpc/pod/' + self.getName() + '/render/' + key;
if (!rpc.method) {
rpc.method = 'GET';
}
if (!rpc.name) {
rpc.name = key;
}
});
//
// --- CREATE RESOURCES
//
// create resources for Actions
this.$resource.dao = dao;
this.$resource.moment = moment;
this.$resource.mime = mime;
this.$resource.uuid = uuid;
this.$resource.tldtools = tldtools;
this.$resource.sanitize = validator.sanitize;
this.$resource._ = _;
this.$resource.accumulateFilter = this.accumulateFilter;
this.$resource.dupFilter = this.dupFilter;
this.$resource.deltaFilter = this.deltaFilter;
this.$resource.options = self.options;
this.$resource.log = (function(scope) {
return function() {
scope.log.apply(scope, arguments);
}
})(this);
this.$resource.getDataSourceName = function(dsName) {
return 'pod_' + self.getName().replace(/-/g, '_') + '_' + dsName;
};
this.$resource.getDataDir = this.getDataDir;
this.$resource.getCDNDir = this.getCDNDir;
this.$resource.expireCDNDir = this.expireCDNDir;
this.$resource.getCDNURL = this.getCDNURL;
this.$resource._httpGet = this._httpGet;
this.$resource._httpPost = this._httpPost;
this.$resource._httpPut = this._httpPut;
this.$resource._httpStreamToFile = this._httpStreamToFile;
this.$resource.helper = helper;
this.$resource.stream = {
toHash : helper.streamToHash,
toBuffer : helper.streamToBuffer
}
// temporary file management bridge
this.$resource.file = cdn;
/*
this.$resource.file = {
get : this._cdnFileGet
}
*/
this.$resource._isVisibleHost = this._isVisibleHost;
// give the pod a scheduler
if (options.isMaster) {
this.$resource.cron = cron;
}
// --------- BIND ACTIONS
// bind actions
var action;
_.each(this.getActionSchemas(), function(schema, actionName) {
if (!schema.disabled) {
var reqBase = self.getPodBase(podName, options.reqLiteral),
actionProto = require(reqBase + '/' + actionName + '.js');
action = new actionProto(self.getConfig(), self);
action.$resource = self.$resource;
// bind meta info
action.name = actionName;
action.schema = schema;
action.pod = self;
// add to action collection
self.actions[actionName] = action;
} else {
// drop disabled schemas
delete self.getActionSchemas()[actionName];
}
});
this._limiters = {
maxRate : this.getRateLimit(),
owners : {}
};
if (this._podInit) {
this._podInit.apply(this);
}
},
// tests whether host is in blacklist
hostBlacklisted : function(host, whitelist, next) {
var blacklist = this.options.blacklist;
helper.resolveHost(host, function(err, aRecords, resolvedHost) {
var inBlacklist = false;
if (!err) {
if (whitelist) {
if (_.intersection(aRecords, whitelist).length ) {
next(err, [], aRecords);
return;
} else {
for (var i = 0; i < whitelist.length; i++) {
if (resolvedHost === whitelist[i]) {
next(err, [], aRecords);
return;
}
}
}
}
inBlacklist = _.intersection(aRecords, blacklist)
}
next(err, inBlacklist, aRecords);
});
},
_isVisibleHost : function(host, next, channel, whitelist) {
var self = this;
self.hostBlacklisted(host, whitelist, function(err, blacklisted, resolved) {
if (err) {
next(err);
if (channel) {
self.log(err, channel, 'error');
} else {
self._logger.call(self, err, 'error');
}
} else {
next(err, blacklisted, resolved);
}
});
},
/**
* Retrieves matching elements from the manfiest with a JSON Path
* When no element found, returns null
*
* @param string path JSONPath
* @returns mixed result or null
*/
_attrCache : {},
getBPMAttr : function (path) {
var val;
if (true || !this._attrCache[path]) {
var result = helper.JSONPath(this._bpm, path);
if (result.length === 1) {
val = result[0];
} else if (result.length) {
val = result;
} else {
val = null;
}
this._attrCache[path] = val;
}
return this._attrCache[path];
},
getSchema : function() {
return this._bpm;
},
setSchema : function(bpmJSON) {
this._bpm = bpmJSON;
},
// --------------------------- BPM path accessors
getName : function() {
return this.getBPMAttr('name');
},
getTitle : function() {
return this.getBPMAttr('title');
},
getDescription : function() {
return this.getBPMAttr('description');
},
getIcon : function() {
return this.options.cdnPublicBaseURL + '/pods/' + this.getName() + '.png';
},
getRateLimit : function() {
return this.getBPMAttr('rateLimit');
},
getRPCs : function(rpc) {
return this.getBPMAttr('rpcs' + (rpc ? ('.' + rpc) : '' )) || {};
},
getTrackDuplicates : function() {
return this.getBPMAttr('trackDuplicates') || false;
},
getTrackDeltas : function() {
return this.getBPMAttr('trackDeltas') || false;
},
getTags : function() {
return this.getBPMAttr('tags');
},
// AUTH
getAuthType : function() {
return this.getBPMAttr('auth.strategy') || 'none';
},
getAuthProperties : function() {
return this.getBPMAttr('auth.properties') || {};
},
getAuthDisposition : function() {
return this.getBPMAttr('auth.disposition') || [];
},
getAuth : function() {
var auth = this.getBPMAttr('auth');
auth.status = 'none' === auth.strategy ? 'accepted' : 'required'
return auth;
},
// POD CONFIG
getConfig : function() {
return this.getBPMAttr('config') || {};
},
setConfig: function(config) {
this._bpm.config = config;
},
// DATASOURCES
getDataSources : function() {
return this.getBPMAttr('dataSources') || {};
},
getDataSourceName : function(dsName) {
return 'pod_' + this.getName().replace(/-/g, '_') + '_' + dsName;
},
// DAO
setDao: function(dao) {
this._dao = dao;
},
getDao: function() {
return this._dao;
},
// --------------------------- BPM ACTION Path Accessors
getTriggerType : function(action) {
return this.getBPMAttr('actions.' + action + '.trigger');
},
getActionSchemas : function() {
return this.getBPMAttr('actions');
},
getAction : function(action) {
return this.getBPMAttr('actions.' + action);
},
getActionConfig : function(action) {
return this.getBPMAttr('actions.' + action + '.config');
},
getActionExports : function(action) {
return this.getBPMAttr('actions.' + action + '.exports');
},
getActionImports : function(action) {
return this.getBPMAttr('actions.' + action + '.imports');
},
getActionRPCs : function(action, rpc) {
return this.getBPMAttr('actions.' + action + '.rpcs' + (rpc ? ('.' + rpc) : ''));
},
getActionConfigDefaults : function(action) {
var defaults = {},
config = this.getActionConfig(action);
_.each(config.properties, function(attr, key) {
if (attr['default']) {
defaults[key] = attr['default'];
}
});
return defaults;
},
getActionImportDefaults : function(action) {
var defaults = {},
imports = this.getActionImports(action);
_.each(imports.properties, function(attr, key) {
if (attr['default']) {
defaults[key] = attr['default'];
}
});
return defaults;
},
getActionRPC : function(action, rpc) {
return this.getBPMAttr('actions.' + action + '.rpcs.' + rpc);
},
// description of the action
getActionDescription : function(action) {
return this.getAction(action).description;
},
// alias for getActionDescription
repr : function() {
return this.getActionDescription.apply(this, arguments);
},
// --------------------------- Compound tests and helpers
// invoker for this action can generate its own content (periodically)
isTrigger: function(action) {
var tt = this.getTriggerType(action);
return ('poll' === tt || 'realtime' === tt);
},
isRealtime : function(action) {
var tt = this.getTriggerType(action);
return ('realtime' === tt);
},
// action can render its own stored content
canRender: function(action) {
return this.getBPMAttr('actions.' + action + '.rpcs') !== null;
},
// tests whether renderer is available for an action
isRenderer : function(action, renderer) {
return 'invoke' === renderer || this.getBPMAttr('actions.' + action + '.rpcs.' + renderer) !== null;
},
testImport : function(action, importName) {
return this.getBPMAttr('actions.' + action + '.imports.' + importName)
},
listActions : function() {
return _.where(this.getActionSchemas(), { trigger : 'invoke'} );
},
listEmitters : function() {
// return this.getBPMAttr('.actions[?(@.trigger!="invoke")]');
return _.filter(this.getActionSchemas(), function(action, key) {
return (action.trigger !== 'invoke');
});
},
// provide a scheduler service
registerCron : function(id, period, callback) {
var self = this;
if (this.$resource.cron) {
if (!this.crons[id]) {
self._logger.call(self, 'POD:Registering Cron:' + self.getName() + ':' + id);
self.crons[id] = new self.$resource.cron.CronJob(
period,
callback,
null,
true,
self.options.timezone
);
}
}
},
// limit the rate at which a fn call can be made.
_ratePopper : null,
limitRate : function(channel, fn, rateOverride) {
var queue,
limiters = this._limiters.owners,
rateOverride = rateOverride || this._limiters.maxRate;
if (!limiters[channel.owner_id]) {
limiters[channel.owner_id] = {
queue : []
}
}
limiters[channel.owner_id].queue.push(fn);
if (!limiters[channel.owner_id].popper) {
limiters[channel.owner_id].popper = setInterval(function() {
if (limiters[channel.owner_id].queue.length) {
limiters[channel.owner_id].queue.shift()();
} else {
clearInterval(limiters[channel.owner_id].popper);
delete limiters[channel.owner_id]
}
}, 1000 / rateOverride);
}
},
/**
* Logs a message
*/
log : function(message, channel, level) {
if (helper.isObject(message)) {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system'),
level);
this._logger.call(this, message, level);
} else {
this._logger.call(this,
channel.action
+ ':'
+ (channel.owner_id ? channel.owner_id : 'system')
+ ':'
+ message,
level);
}
},
// ------------------------------ 3RD PARTY AUTHENTICATION HELPERS
testCredentials : function(struct, next) {
next(false);
},
issuerTokenRPC : function(method, req, res) {
var ok = false,
accountId = req.remoteUser.user.id;
self = this;
res.contentType(DEFS.CONTENTTYPE_JSON);
if (this.getAuthType() == 'issuer_token') {
if (method == 'set') {
self._logger.call(self, '[' + accountId + '] ISSUER_TOKEN ' + this.getName() + ' SET' );
// upsert oAuth document
var filter = {
owner_id : accountId,
type : this.getAuthType(),
auth_provider : this.getName()
};
var struct = {
owner_id : accountId,
username : req.query.username,
key : req.query.key,
password : req.query.password,
type : this.getAuthType(),
auth_provider : this.getName()
};
self.testCredentials(struct, function(err, status) {
if (err) {
res.status(status || 401).jsonp({ "message" : err.toString() });
} else {
// @todo upserts don't work with mongoose middleware
// create a dao helper for filter -> model upsert.
self._dao.find('account_auth', filter, function(err, result) {
if (err) {
self._logger.call(self, err, 'error');
res.send(500);
} else {
// update
if (result) {
self._dao.update('account_auth', result.id, struct, function(err, result) {
if (err) {
self._logger.call(self, err, 'error');
res.status(500).jsonp({});
} else {
res.status(200).jsonp({});
}
}, req.remoteUser);
} else {
// create
var model = self._dao.modelFactory('account_auth', struct);
self._dao.create(model, function(err, result) {
if (err) {
self._logger.call(self, err, 'error');
res.status(500).jsonp({});
} else {
res.status(200).jsonp({});
}
}, req.remoteUser);
}
}
});
}
});
ok = true;
} else if (method == 'deauth') {
var filter = {
owner_id : accountId,
type : 'issuer_token',
auth_provider : this.getName()
}
this._dao.removeFilter('account_auth', filter, function(err) {
if (!err) {
res.status(200).jsonp({});
} else {
self._logger.call(self, err, 'error');
res.status(500).jsonp({});
}
});
ok = true;
}
}
return ok;
},
/**
* @param string method auth rpc method name
* @param object req request
* @param object res response
*/
oAuthRPC: function(method, req, res) {
var ok = false,
authMethod = (this._oAuthMethod) ? this._oAuthMethod : 'authorize',
self = this,
podName = this.getName(),
accountInfo = req.remoteUser,
accountId = accountInfo.getId(),
emitterHost = this.options.emitterBaseURL;
if (false !== this._oAuthRegistered) {
// invoke the passport oauth handler
if (method == 'auth') {
self._logger.call(self, '[' + accountId + '] OAUTH ' + podName + ' AUTH REQUEST' );
passport[authMethod](this.getName(), this._oAuthConfig)(req, res);
ok = true;
} else if (method == 'cb') {
self._logger.call(self, '[' + accountId + '] OAUTH ' + podName + ' AUTH CALLBACK ' + authMethod );
passport[authMethod](this.getName(), function(err, user) {
// @todo - decouple from site.
if (err) {
self._logger.call(self, err, 'error');
res.redirect(emitterHost + '/oauthcb?status=denied&provider=' + podName);
} else if (!user && req.query.error_reason && req.query.error_reason == 'user_denied') {
self._logger.call(self, '[' + accountId + '] OAUTH ' + podName + ' CANCELLED' );
res.redirect(emitterHost + '/oauthcb?status=denied&provider=' + podName);
} else if (!user) {
self._logger.call(self, '[' + accountId + '] OAUTH ' + podName + ' UNKNOWN ERROR' );
res.redirect(emitterHost + '/oauthcb?status=denied&provider=' + podName);
} else {
self._logger.call(self, '[' + accountId + '] OAUTH ' + podName + ' AUTHORIZED' );
// install singletons
// self.autoInstall(accountInfo);
res.redirect(emitterHost + '/oauthcb?status=accepted&provider=' + podName);
}
})(req, res, function(err) {
res.send(500);
self._logger.call(self, err, 'error');
});
ok = true;
} else if (method == 'deauth') {
this.oAuthUnbind(accountId, function(err) {
if (!err) {
res.sendStatus(200);
} else {
self._logger.call(self, err, 'error');
res.sendStatus(500);
}
});
ok = true;