dauth-md-node 0.1.71 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ export declare function getUser(token: string, domainName: string): Promise<{
2
+ response: any;
3
+ data: any;
4
+ }>;
@@ -6,8 +6,379 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau
6
6
 
7
7
  var jwt = _interopDefault(require('jsonwebtoken'));
8
8
 
9
+ function _regeneratorRuntime() {
10
+ _regeneratorRuntime = function () {
11
+ return e;
12
+ };
13
+ var t,
14
+ e = {},
15
+ r = Object.prototype,
16
+ n = r.hasOwnProperty,
17
+ o = Object.defineProperty || function (t, e, r) {
18
+ t[e] = r.value;
19
+ },
20
+ i = "function" == typeof Symbol ? Symbol : {},
21
+ a = i.iterator || "@@iterator",
22
+ c = i.asyncIterator || "@@asyncIterator",
23
+ u = i.toStringTag || "@@toStringTag";
24
+ function define(t, e, r) {
25
+ return Object.defineProperty(t, e, {
26
+ value: r,
27
+ enumerable: !0,
28
+ configurable: !0,
29
+ writable: !0
30
+ }), t[e];
31
+ }
32
+ try {
33
+ define({}, "");
34
+ } catch (t) {
35
+ define = function (t, e, r) {
36
+ return t[e] = r;
37
+ };
38
+ }
39
+ function wrap(t, e, r, n) {
40
+ var i = e && e.prototype instanceof Generator ? e : Generator,
41
+ a = Object.create(i.prototype),
42
+ c = new Context(n || []);
43
+ return o(a, "_invoke", {
44
+ value: makeInvokeMethod(t, r, c)
45
+ }), a;
46
+ }
47
+ function tryCatch(t, e, r) {
48
+ try {
49
+ return {
50
+ type: "normal",
51
+ arg: t.call(e, r)
52
+ };
53
+ } catch (t) {
54
+ return {
55
+ type: "throw",
56
+ arg: t
57
+ };
58
+ }
59
+ }
60
+ e.wrap = wrap;
61
+ var h = "suspendedStart",
62
+ l = "suspendedYield",
63
+ f = "executing",
64
+ s = "completed",
65
+ y = {};
66
+ function Generator() {}
67
+ function GeneratorFunction() {}
68
+ function GeneratorFunctionPrototype() {}
69
+ var p = {};
70
+ define(p, a, function () {
71
+ return this;
72
+ });
73
+ var d = Object.getPrototypeOf,
74
+ v = d && d(d(values([])));
75
+ v && v !== r && n.call(v, a) && (p = v);
76
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
77
+ function defineIteratorMethods(t) {
78
+ ["next", "throw", "return"].forEach(function (e) {
79
+ define(t, e, function (t) {
80
+ return this._invoke(e, t);
81
+ });
82
+ });
83
+ }
84
+ function AsyncIterator(t, e) {
85
+ function invoke(r, o, i, a) {
86
+ var c = tryCatch(t[r], t, o);
87
+ if ("throw" !== c.type) {
88
+ var u = c.arg,
89
+ h = u.value;
90
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
91
+ invoke("next", t, i, a);
92
+ }, function (t) {
93
+ invoke("throw", t, i, a);
94
+ }) : e.resolve(h).then(function (t) {
95
+ u.value = t, i(u);
96
+ }, function (t) {
97
+ return invoke("throw", t, i, a);
98
+ });
99
+ }
100
+ a(c.arg);
101
+ }
102
+ var r;
103
+ o(this, "_invoke", {
104
+ value: function (t, n) {
105
+ function callInvokeWithMethodAndArg() {
106
+ return new e(function (e, r) {
107
+ invoke(t, n, e, r);
108
+ });
109
+ }
110
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
111
+ }
112
+ });
113
+ }
114
+ function makeInvokeMethod(e, r, n) {
115
+ var o = h;
116
+ return function (i, a) {
117
+ if (o === f) throw new Error("Generator is already running");
118
+ if (o === s) {
119
+ if ("throw" === i) throw a;
120
+ return {
121
+ value: t,
122
+ done: !0
123
+ };
124
+ }
125
+ for (n.method = i, n.arg = a;;) {
126
+ var c = n.delegate;
127
+ if (c) {
128
+ var u = maybeInvokeDelegate(c, n);
129
+ if (u) {
130
+ if (u === y) continue;
131
+ return u;
132
+ }
133
+ }
134
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
135
+ if (o === h) throw o = s, n.arg;
136
+ n.dispatchException(n.arg);
137
+ } else "return" === n.method && n.abrupt("return", n.arg);
138
+ o = f;
139
+ var p = tryCatch(e, r, n);
140
+ if ("normal" === p.type) {
141
+ if (o = n.done ? s : l, p.arg === y) continue;
142
+ return {
143
+ value: p.arg,
144
+ done: n.done
145
+ };
146
+ }
147
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
148
+ }
149
+ };
150
+ }
151
+ function maybeInvokeDelegate(e, r) {
152
+ var n = r.method,
153
+ o = e.iterator[n];
154
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
155
+ var i = tryCatch(o, e.iterator, r.arg);
156
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
157
+ var a = i.arg;
158
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
159
+ }
160
+ function pushTryEntry(t) {
161
+ var e = {
162
+ tryLoc: t[0]
163
+ };
164
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
165
+ }
166
+ function resetTryEntry(t) {
167
+ var e = t.completion || {};
168
+ e.type = "normal", delete e.arg, t.completion = e;
169
+ }
170
+ function Context(t) {
171
+ this.tryEntries = [{
172
+ tryLoc: "root"
173
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
174
+ }
175
+ function values(e) {
176
+ if (e || "" === e) {
177
+ var r = e[a];
178
+ if (r) return r.call(e);
179
+ if ("function" == typeof e.next) return e;
180
+ if (!isNaN(e.length)) {
181
+ var o = -1,
182
+ i = function next() {
183
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
184
+ return next.value = t, next.done = !0, next;
185
+ };
186
+ return i.next = i;
187
+ }
188
+ }
189
+ throw new TypeError(typeof e + " is not iterable");
190
+ }
191
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
192
+ value: GeneratorFunctionPrototype,
193
+ configurable: !0
194
+ }), o(GeneratorFunctionPrototype, "constructor", {
195
+ value: GeneratorFunction,
196
+ configurable: !0
197
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
198
+ var e = "function" == typeof t && t.constructor;
199
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
200
+ }, e.mark = function (t) {
201
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
202
+ }, e.awrap = function (t) {
203
+ return {
204
+ __await: t
205
+ };
206
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
207
+ return this;
208
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
209
+ void 0 === i && (i = Promise);
210
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
211
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
212
+ return t.done ? t.value : a.next();
213
+ });
214
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
215
+ return this;
216
+ }), define(g, "toString", function () {
217
+ return "[object Generator]";
218
+ }), e.keys = function (t) {
219
+ var e = Object(t),
220
+ r = [];
221
+ for (var n in e) r.push(n);
222
+ return r.reverse(), function next() {
223
+ for (; r.length;) {
224
+ var t = r.pop();
225
+ if (t in e) return next.value = t, next.done = !1, next;
226
+ }
227
+ return next.done = !0, next;
228
+ };
229
+ }, e.values = values, Context.prototype = {
230
+ constructor: Context,
231
+ reset: function (e) {
232
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
233
+ },
234
+ stop: function () {
235
+ this.done = !0;
236
+ var t = this.tryEntries[0].completion;
237
+ if ("throw" === t.type) throw t.arg;
238
+ return this.rval;
239
+ },
240
+ dispatchException: function (e) {
241
+ if (this.done) throw e;
242
+ var r = this;
243
+ function handle(n, o) {
244
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
245
+ }
246
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
247
+ var i = this.tryEntries[o],
248
+ a = i.completion;
249
+ if ("root" === i.tryLoc) return handle("end");
250
+ if (i.tryLoc <= this.prev) {
251
+ var c = n.call(i, "catchLoc"),
252
+ u = n.call(i, "finallyLoc");
253
+ if (c && u) {
254
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
255
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
256
+ } else if (c) {
257
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
258
+ } else {
259
+ if (!u) throw new Error("try statement without catch or finally");
260
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
261
+ }
262
+ }
263
+ }
264
+ },
265
+ abrupt: function (t, e) {
266
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
267
+ var o = this.tryEntries[r];
268
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
269
+ var i = o;
270
+ break;
271
+ }
272
+ }
273
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
274
+ var a = i ? i.completion : {};
275
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
276
+ },
277
+ complete: function (t, e) {
278
+ if ("throw" === t.type) throw t.arg;
279
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
280
+ },
281
+ finish: function (t) {
282
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
283
+ var r = this.tryEntries[e];
284
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
285
+ }
286
+ },
287
+ catch: function (t) {
288
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
289
+ var r = this.tryEntries[e];
290
+ if (r.tryLoc === t) {
291
+ var n = r.completion;
292
+ if ("throw" === n.type) {
293
+ var o = n.arg;
294
+ resetTryEntry(r);
295
+ }
296
+ return o;
297
+ }
298
+ }
299
+ throw new Error("illegal catch attempt");
300
+ },
301
+ delegateYield: function (e, r, n) {
302
+ return this.delegate = {
303
+ iterator: values(e),
304
+ resultName: r,
305
+ nextLoc: n
306
+ }, "next" === this.method && (this.arg = t), y;
307
+ }
308
+ }, e;
309
+ }
310
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
311
+ try {
312
+ var info = gen[key](arg);
313
+ var value = info.value;
314
+ } catch (error) {
315
+ reject(error);
316
+ return;
317
+ }
318
+ if (info.done) {
319
+ resolve(value);
320
+ } else {
321
+ Promise.resolve(value).then(_next, _throw);
322
+ }
323
+ }
324
+ function _asyncToGenerator(fn) {
325
+ return function () {
326
+ var self = this,
327
+ args = arguments;
328
+ return new Promise(function (resolve, reject) {
329
+ var gen = fn.apply(self, args);
330
+ function _next(value) {
331
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
332
+ }
333
+ function _throw(err) {
334
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
335
+ }
336
+ _next(undefined);
337
+ });
338
+ };
339
+ }
340
+
341
+ var fetch = /*#__PURE__*/require('node-fetch');
342
+ function getUser(_x, _x2) {
343
+ return _getUser.apply(this, arguments);
344
+ }
345
+ function _getUser() {
346
+ _getUser = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(token, domainName) {
347
+ var params, response, data;
348
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
349
+ while (1) switch (_context.prev = _context.next) {
350
+ case 0:
351
+ params = {
352
+ method: 'GET',
353
+ headers: {
354
+ Authorization: token,
355
+ 'Content-Type': 'application/json'
356
+ }
357
+ };
358
+ _context.next = 3;
359
+ return fetch("http://localhost:4012/api/v1/get-tenant-user/" + domainName, params);
360
+ case 3:
361
+ response = _context.sent;
362
+ _context.next = 6;
363
+ return response.json();
364
+ case 6:
365
+ data = _context.sent;
366
+ return _context.abrupt("return", {
367
+ response: response,
368
+ data: data
369
+ });
370
+ case 8:
371
+ case "end":
372
+ return _context.stop();
373
+ }
374
+ }, _callee);
375
+ }));
376
+ return _getUser.apply(this, arguments);
377
+ }
378
+
9
379
  var dauth = function dauth(_ref) {
10
- var ssid = _ref.ssid;
380
+ var ssid = _ref.ssid,
381
+ domainName = _ref.domainName;
11
382
  return function (req, res, next) {
12
383
  if (!req.headers.authorization) {
13
384
  return res.status(403).send({
@@ -17,22 +388,46 @@ var dauth = function dauth(_ref) {
17
388
  }
18
389
  var token = req.headers.authorization.replace(/['"]+/g, '');
19
390
  try {
20
- var payload = jwt.verify(token, ssid);
21
- req.user = payload;
22
- return next();
391
+ jwt.verify(token, ssid);
392
+ // req.user = payload;
393
+ getUser(token, domainName).then(function (getUserFetch) {
394
+ if (getUserFetch.response.status === 404) {
395
+ return res.status(404).send({
396
+ status: 'domain-not-found',
397
+ message: 'Dauth domain does not exist'
398
+ });
399
+ } else if (getUserFetch.response.status === 500) {
400
+ return res.status(500).send({
401
+ status: 'error',
402
+ message: 'Dauth server error'
403
+ });
404
+ } else if (getUserFetch.response.status === 200) {
405
+ req.user = getUserFetch.data.user;
406
+ // console.log('node-fetch npm', req.user);
407
+ return next();
408
+ } else {
409
+ return res.status(501).send({
410
+ status: 'error',
411
+ message: 'Dauth server error'
412
+ });
413
+ }
414
+ })["catch"](function (error) {
415
+ console.log('getDauthUser error', error);
416
+ return next();
417
+ });
23
418
  } catch (error) {
24
419
  if (error && (error == null ? void 0 : error.message) === 'jwt expired') {
25
420
  return res.status(500).send({
26
421
  status: 'token-expired',
27
422
  message: 'El token ha expirado',
28
- error: error,
423
+ // error: error,
29
424
  mdKey: 'ensure_auth'
30
425
  });
31
426
  }
32
427
  return res.status(500).send({
33
428
  status: 'token-invalid',
34
429
  message: 'El token no es válido',
35
- error: error,
430
+ // error: error,
36
431
  mdKey: 'ensure_auth'
37
432
  });
38
433
  }
@@ -1 +1 @@
1
- {"version":3,"file":"dauth-md-node.cjs.development.js","sources":["../src/index.ts"],"sourcesContent":["import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid }: { ssid: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n const payload = jwt.verify(token, ssid as string) as IAccessToken;\n req.user = payload;\n return next();\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["dauth","_ref","ssid","req","res","next","headers","authorization","status","send","mdKey","token","replace","payload","jwt","verify","user","error","message"],"mappings":";;;;;;;;IAoCaA,KAAK,GAAG,SAARA,KAAKA,CAAAC,IAAA;MAAMC,IAAI,GAAAD,IAAA,CAAJC,IAAI;EAC1B,OAAO,UACLC,GAAiB,EACjBC,GAAoB,EACpBC,IAAkB;IAElB,IAAI,CAACF,GAAG,CAACG,OAAO,CAACC,aAAa,EAAE;MAC9B,OAAOH,GAAG,CACPI,MAAM,CAAC,GAAG,CAAC,CACXC,IAAI,CAAC;QAAED,MAAM,EAAE,iBAAiB;QAAEE,KAAK,EAAE;OAAe,CAAC;;IAE9D,IAAMC,KAAK,GAAGR,GAAG,CAACG,OAAO,CAACC,aAAa,CAACK,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC7D,IAAI;MACF,IAAMC,OAAO,GAAGC,GAAG,CAACC,MAAM,CAACJ,KAAK,EAAET,IAAc,CAAiB;MACjEC,GAAG,CAACa,IAAI,GAAGH,OAAO;MAClB,OAAOR,IAAI,EAAE;KACd,CAAC,OAAOY,KAAK,EAAE;MACd,IAAIA,KAAK,IAAI,CAAAA,KAAK,oBAALA,KAAK,CAAEC,OAAO,MAAK,aAAa,EAAE;QAC7C,OAAOd,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;UAC1BD,MAAM,EAAE,eAAe;UACvBU,OAAO,EAAE,sBAAsB;UAC/BD,KAAK,EAAEA,KAAK;UACZP,KAAK,EAAE;SACR,CAAC;;MAEJ,OAAON,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;QAC1BD,MAAM,EAAE,eAAe;QACvBU,OAAO,EAAE,uBAAuB;QAChCD,KAAK,EAAEA,KAAK;QACZP,KAAK,EAAE;OACR,CAAC;;GAEL;AACH;;;;"}
1
+ {"version":3,"file":"dauth-md-node.cjs.development.js","sources":["../src/api/dauth.api.ts","../src/index.ts"],"sourcesContent":["const fetch = require('node-fetch');\n\nexport async function getUser(token: string, domainName: string) {\n const params = {\n method: 'GET',\n headers: {\n Authorization: token,\n 'Content-Type': 'application/json',\n },\n };\n const response = await fetch(\n `http://localhost:4012/api/v1/get-tenant-user/${domainName}`,\n params\n );\n const data = await response.json();\n return { response, data };\n}","import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\nimport { getUser } from './api/dauth.api';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid, domainName }: { ssid: string, domainName: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n jwt.verify(token, ssid as string) as IAccessToken;\n // req.user = payload;\n getUser(token, domainName)\n .then((getUserFetch: any) => {\n if (getUserFetch.response.status === 404) {\n return res.status(404).send({\n status: 'domain-not-found',\n message: 'Dauth domain does not exist',\n });\n } else if (getUserFetch.response.status === 500) {\n return res\n .status(500)\n .send({ status: 'error', message: 'Dauth server error' });\n } else if (getUserFetch.response.status === 200) {\n req.user = getUserFetch.data.user;\n // console.log('node-fetch npm', req.user);\n return next();\n } else {\n return res.status(501).send({\n status: 'error',\n message: 'Dauth server error',\n });\n }\n })\n .catch((error: any) => {\n console.log('getDauthUser error', error);\n return next();\n });\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["fetch","require","getUser","_x","_x2","_getUser","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","token","domainName","params","response","data","wrap","_callee$","_context","prev","next","method","headers","Authorization","sent","json","abrupt","stop","dauth","_ref","ssid","req","res","authorization","status","send","mdKey","replace","jwt","verify","then","getUserFetch","message","user","error","console","log"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAMA,KAAK,gBAAGC,OAAO,CAAC,YAAY,CAAC;SAEbC,OAAOA,CAAAC,EAAA,EAAAC,GAAA;EAAA,OAAAC,QAAA,CAAAC,KAAA,OAAAC,SAAA;AAAA;AAc5B,SAAAF;EAAAA,QAAA,GAAAG,iBAAA,eAAAC,mBAAA,GAAAC,IAAA,CAdM,SAAAC,QAAuBC,KAAa,EAAEC,UAAkB;IAAA,IAAAC,MAAA,EAAAC,QAAA,EAAAC,IAAA;IAAA,OAAAP,mBAAA,GAAAQ,IAAA,UAAAC,SAAAC,QAAA;MAAA,kBAAAA,QAAA,CAAAC,IAAA,GAAAD,QAAA,CAAAE,IAAA;QAAA;UACvDP,M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"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("jsonwebtoken"))&&"object"==typeof e&&"default"in e?e.default:e;exports.dauth=function(e){var r=e.ssid;return function(e,s,a){if(!e.headers.authorization)return s.status(403).send({status:"token-not-found",mdKey:"ensure_auth"});var n=e.headers.authorization.replace(/['"]+/g,"");try{var u=t.verify(n,r);return e.user=u,a()}catch(e){return e&&"jwt expired"===(null==e?void 0:e.message)?s.status(500).send({status:"token-expired",message:"El token ha expirado",error:e,mdKey:"ensure_auth"}):s.status(500).send({status:"token-invalid",message:"El token no es válido",error:e,mdKey:"ensure_auth"})}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("jsonwebtoken"))&&"object"==typeof t&&"default"in t?t.default:t;function r(){r=function(){return e};var t,e={},n=Object.prototype,o=n.hasOwnProperty,a=Object.defineProperty||function(t,e,r){t[e]=r.value},i="function"==typeof Symbol?Symbol:{},u=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function h(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{h({},"")}catch(t){h=function(t,e,r){return t[e]=r}}function f(t,e,r,n){var o=Object.create((e&&e.prototype instanceof g?e:g).prototype),i=new N(n||[]);return a(o,"_invoke",{value:k(t,r,i)}),o}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=f;var p="suspendedStart",d="executing",v="completed",y={};function g(){}function m(){}function w(){}var x={};h(x,u,(function(){return this}));var b=Object.getPrototypeOf,L=b&&b(b(T([])));L&&L!==n&&o.call(L,u)&&(x=L);var E=w.prototype=g.prototype=Object.create(x);function _(t){["next","throw","return"].forEach((function(e){h(t,e,(function(t){return this._invoke(e,t)}))}))}function j(t,e){function r(n,a,i,u){var s=l(t[n],t,a);if("throw"!==s.type){var c=s.arg,h=c.value;return h&&"object"==typeof h&&o.call(h,"__await")?e.resolve(h.__await).then((function(t){r("next",t,i,u)}),(function(t){r("throw",t,i,u)})):e.resolve(h).then((function(t){c.value=t,i(c)}),(function(t){return r("throw",t,i,u)}))}u(s.arg)}var n;a(this,"_invoke",{value:function(t,o){function a(){return new e((function(e,n){r(t,o,e,n)}))}return n=n?n.then(a,a):a()}})}function k(e,r,n){var o=p;return function(a,i){if(o===d)throw new Error("Generator is already running");if(o===v){if("throw"===a)throw i;return{value:t,done:!0}}for(n.method=a,n.arg=i;;){var u=n.delegate;if(u){var s=O(u,n);if(s){if(s===y)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(o===p)throw o=v,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);o=d;var c=l(e,r,n);if("normal"===c.type){if(o=n.done?v:"suspendedYield",c.arg===y)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(o=v,n.method="throw",n.arg=c.arg)}}}function O(e,r){var n=r.method,o=e.iterator[n];if(o===t)return r.delegate=null,"throw"===n&&e.iterator.return&&(r.method="return",r.arg=t,O(e,r),"throw"===r.method)||"return"!==n&&(r.method="throw",r.arg=new TypeError("The iterator does not provide a '"+n+"' method")),y;var a=l(o,e.iterator,r.arg);if("throw"===a.type)return r.method="throw",r.arg=a.arg,r.delegate=null,y;var i=a.arg;return i?i.done?(r[e.resultName]=i.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,y):i:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,y)}function P(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function G(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(P,this),this.reset(!0)}function T(e){if(e||""===e){var r=e[u];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,a=function r(){for(;++n<e.length;)if(o.call(e,n))return r.value=e[n],r.done=!1,r;return r.value=t,r.done=!0,r};return a.next=a}}throw new TypeError(typeof e+" is not iterable")}return m.prototype=w,a(E,"constructor",{value:w,configurable:!0}),a(w,"constructor",{value:m,configurable:!0}),m.displayName=h(w,c,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===m||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,w):(t.__proto__=w,h(t,c,"GeneratorFunction")),t.prototype=Object.create(E),t},e.awrap=function(t){return{__await:t}},_(j.prototype),h(j.prototype,s,(function(){return this})),e.AsyncIterator=j,e.async=function(t,r,n,o,a){void 0===a&&(a=Promise);var i=new j(f(t,r,n,o),a);return e.isGeneratorFunction(r)?i:i.next().then((function(t){return t.done?t.value:i.next()}))},_(E),h(E,c,"Generator"),h(E,u,(function(){return this})),h(E,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},e.values=T,N.prototype={constructor:N,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=t,this.done=!1,this.delegate=null,this.method="next",this.arg=t,this.tryEntries.forEach(G),!e)for(var r in this)"t"===r.charAt(0)&&o.call(this,r)&&!isNaN(+r.slice(1))&&(this[r]=t)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var r=this;function n(n,o){return u.type="throw",u.arg=e,r.next=n,o&&(r.method="next",r.arg=t),!!o}for(var a=this.tryEntries.length-1;a>=0;--a){var i=this.tryEntries[a],u=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=o.call(i,"catchLoc"),c=o.call(i,"finallyLoc");if(s&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&o.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var a=n;break}}a&&("break"===t||"continue"===t)&&a.tryLoc<=e&&e<=a.finallyLoc&&(a=null);var i=a?a.completion:{};return i.type=t,i.arg=e,a?(this.method="next",this.next=a.finallyLoc,y):this.complete(i)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),y},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),G(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;G(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:T(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},e}function n(t,e,r,n,o,a,i){try{var u=t[a](i),s=u.value}catch(t){return void r(t)}u.done?e(s):Promise.resolve(s).then(n,o)}function o(t){return function(){var e=this,r=arguments;return new Promise((function(o,a){var i=t.apply(e,r);function u(t){n(i,o,a,u,s,"next",t)}function s(t){n(i,o,a,u,s,"throw",t)}u(void 0)}))}}var a=require("node-fetch");function i(){return(i=o(r().mark((function t(e,n){var o,i;return r().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o={method:"GET",headers:{Authorization:e,"Content-Type":"application/json"}},t.next=3,a("http://localhost:4012/api/v1/get-tenant-user/"+n,o);case 3:return i=t.sent,t.next=6,i.json();case 6:return t.abrupt("return",{response:i,data:t.sent});case 8:case"end":return t.stop()}}),t)})))).apply(this,arguments)}exports.dauth=function(t){var r=t.ssid,n=t.domainName;return function(t,o,a){if(!t.headers.authorization)return o.status(403).send({status:"token-not-found",mdKey:"ensure_auth"});var u=t.headers.authorization.replace(/['"]+/g,"");try{e.verify(u,r),function(t,e){return i.apply(this,arguments)}(u,n).then((function(e){return 404===e.response.status?o.status(404).send({status:"domain-not-found",message:"Dauth domain does not exist"}):500===e.response.status?o.status(500).send({status:"error",message:"Dauth server error"}):200===e.response.status?(t.user=e.data.user,a()):o.status(501).send({status:"error",message:"Dauth server error"})})).catch((function(t){return console.log("getDauthUser error",t),a()}))}catch(t){return t&&"jwt expired"===(null==t?void 0:t.message)?o.status(500).send({status:"token-expired",message:"El token ha expirado",mdKey:"ensure_auth"}):o.status(500).send({status:"token-invalid",message:"El token no es válido",mdKey:"ensure_auth"})}}};
2
2
  //# sourceMappingURL=dauth-md-node.cjs.production.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dauth-md-node.cjs.production.min.js","sources":["../src/index.ts"],"sourcesContent":["import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid }: { ssid: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n const payload = jwt.verify(token, ssid as string) as IAccessToken;\n req.user = payload;\n return next();\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["_ref","ssid","req","res","next","headers","authorization","status","send","mdKey","token","replace","payload","jwt","verify","user","error","message"],"mappings":"qKAoCqB,SAAHA,OAAMC,EAAID,EAAJC,KACtB,OAAO,SACLC,EACAC,EACAC,GAEA,IAAKF,EAAIG,QAAQC,cACf,OAAOH,EACJI,OAAO,KACPC,KAAK,CAAED,OAAQ,kBAAmBE,MAAO,gBAE9C,IAAMC,EAAQR,EAAIG,QAAQC,cAAcK,QAAQ,SAAU,IAC1D,IACE,IAAMC,EAAUC,EAAIC,OAAOJ,EAAOT,GAElC,OADAC,EAAIa,KAAOH,EACJR,IACP,MAAOY,GACP,OAAIA,GAA4B,uBAAnBA,SAAAA,EAAOC,SACXd,EAAII,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,gBACRU,QAAS,uBACTD,MAAOA,EACPP,MAAO,gBAGJN,EAAII,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,gBACRU,QAAS,wBACTD,MAAOA,EACPP,MAAO"}
1
+ {"version":3,"file":"dauth-md-node.cjs.production.min.js","sources":["../src/api/dauth.api.ts","../src/index.ts"],"sourcesContent":["const fetch = require('node-fetch');\n\nexport async function getUser(token: string, domainName: string) {\n const params = {\n method: 'GET',\n headers: {\n Authorization: token,\n 'Content-Type': 'application/json',\n },\n };\n const response = await fetch(\n `http://localhost:4012/api/v1/get-tenant-user/${domainName}`,\n params\n );\n const data = await response.json();\n return { response, data };\n}","import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\nimport { getUser } from './api/dauth.api';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid, domainName }: { ssid: string, domainName: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n jwt.verify(token, ssid as string) as IAccessToken;\n // req.user = payload;\n getUser(token, domainName)\n .then((getUserFetch: any) => {\n if (getUserFetch.response.status === 404) {\n return res.status(404).send({\n status: 'domain-not-found',\n message: 'Dauth domain does not exist',\n });\n } else if (getUserFetch.response.status === 500) {\n return res\n .status(500)\n .send({ status: 'error', message: 'Dauth server error' });\n } else if (getUserFetch.response.status === 200) {\n req.user = getUserFetch.data.user;\n // console.log('node-fetch npm', req.user);\n return next();\n } else {\n return res.status(501).send({\n status: 'error',\n message: 'Dauth server error',\n });\n }\n })\n .catch((error: any) => {\n console.log('getDauthUser error', error);\n return next();\n });\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["fetch","require","_getUser","_asyncToGenerator","_regeneratorRuntime","mark","_callee","token","domainName","params","response","wrap","_context","prev","next","method","headers","Authorization","Content-Type","sent","json","abrupt","data","stop","apply","arguments","_ref","ssid","req","res","authorization","status","send","mdKey","replace","jwt","verify","_x","_x2","getUser","then","getUserFetch","message","user","error","console","log"],"mappings":"+zNAAA,IAAMA,EAAQC,QAAQ,cAgBrB,SAAAC,IAAA,OAAAA,EAAAC,EAAAC,IAAAC,MAdM,SAAAC,EAAuBC,EAAeC,GAAkB,IAAAC,EAAAC,EAAA,OAAAN,IAAAO,eAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAE,MAAA,OAO5D,OANKL,EAAS,CACbM,OAAQ,MACRC,QAAS,CACPC,cAAeV,EACfW,eAAgB,qBAEnBN,EAAAE,OACsBd,kDAC2BQ,EAChDC,GACD,OAHa,OAARC,EAAQE,EAAAO,KAAAP,EAAAE,OAIKJ,EAASU,OAAM,OAAxB,OAAAR,EAAAS,gBACH,CAAEX,SAAAA,EAAUY,KADTV,EAAAO,OACe,OAAA,UAAA,OAAAP,EAAAW,UAAAjB,QAC1BkB,WAAAC,yBCqBoB,SAAHC,OAAMC,EAAID,EAAJC,KAAMnB,EAAUkB,EAAVlB,WAC5B,OAAO,SACLoB,EACAC,EACAf,GAEA,IAAKc,EAAIZ,QAAQc,cACf,OAAOD,EACJE,OAAO,KACPC,KAAK,CAAED,OAAQ,kBAAmBE,MAAO,gBAE9C,IAAM1B,EAAQqB,EAAIZ,QAAQc,cAAcI,QAAQ,SAAU,IAC1D,IACEC,EAAIC,OAAO7B,EAAOoB,YDhDKU,EAAAC,GAAA,OAAApC,EAAAsB,WAAAC,WCkDvBc,CAAQhC,EAAOC,GACZgC,MAAK,SAACC,GACL,OAAqC,MAAjCA,EAAa/B,SAASqB,OACjBF,EAAIE,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,mBACRW,QAAS,gCAE+B,MAAjCD,EAAa/B,SAASqB,OACxBF,EACJE,OAAO,KACPC,KAAK,CAAED,OAAQ,QAASW,QAAS,uBACM,MAAjCD,EAAa/B,SAASqB,QAC/BH,EAAIe,KAAOF,EAAanB,KAAKqB,KAEtB7B,KAEAe,EAAIE,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,QACRW,QAAS,iCAIR,SAACE,GAEN,OADAC,QAAQC,IAAI,qBAAsBF,GAC3B9B,OAEX,MAAO8B,GACP,OAAIA,GAA4B,uBAAnBA,SAAAA,EAAOF,SACXb,EAAIE,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,gBACRW,QAAS,uBAETT,MAAO,gBAGJJ,EAAIE,OAAO,KAAKC,KAAK,CAC1BD,OAAQ,gBACRW,QAAS,wBAETT,MAAO"}
@@ -1,7 +1,378 @@
1
1
  import jwt from 'jsonwebtoken';
2
2
 
3
+ function _regeneratorRuntime() {
4
+ _regeneratorRuntime = function () {
5
+ return e;
6
+ };
7
+ var t,
8
+ e = {},
9
+ r = Object.prototype,
10
+ n = r.hasOwnProperty,
11
+ o = Object.defineProperty || function (t, e, r) {
12
+ t[e] = r.value;
13
+ },
14
+ i = "function" == typeof Symbol ? Symbol : {},
15
+ a = i.iterator || "@@iterator",
16
+ c = i.asyncIterator || "@@asyncIterator",
17
+ u = i.toStringTag || "@@toStringTag";
18
+ function define(t, e, r) {
19
+ return Object.defineProperty(t, e, {
20
+ value: r,
21
+ enumerable: !0,
22
+ configurable: !0,
23
+ writable: !0
24
+ }), t[e];
25
+ }
26
+ try {
27
+ define({}, "");
28
+ } catch (t) {
29
+ define = function (t, e, r) {
30
+ return t[e] = r;
31
+ };
32
+ }
33
+ function wrap(t, e, r, n) {
34
+ var i = e && e.prototype instanceof Generator ? e : Generator,
35
+ a = Object.create(i.prototype),
36
+ c = new Context(n || []);
37
+ return o(a, "_invoke", {
38
+ value: makeInvokeMethod(t, r, c)
39
+ }), a;
40
+ }
41
+ function tryCatch(t, e, r) {
42
+ try {
43
+ return {
44
+ type: "normal",
45
+ arg: t.call(e, r)
46
+ };
47
+ } catch (t) {
48
+ return {
49
+ type: "throw",
50
+ arg: t
51
+ };
52
+ }
53
+ }
54
+ e.wrap = wrap;
55
+ var h = "suspendedStart",
56
+ l = "suspendedYield",
57
+ f = "executing",
58
+ s = "completed",
59
+ y = {};
60
+ function Generator() {}
61
+ function GeneratorFunction() {}
62
+ function GeneratorFunctionPrototype() {}
63
+ var p = {};
64
+ define(p, a, function () {
65
+ return this;
66
+ });
67
+ var d = Object.getPrototypeOf,
68
+ v = d && d(d(values([])));
69
+ v && v !== r && n.call(v, a) && (p = v);
70
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
71
+ function defineIteratorMethods(t) {
72
+ ["next", "throw", "return"].forEach(function (e) {
73
+ define(t, e, function (t) {
74
+ return this._invoke(e, t);
75
+ });
76
+ });
77
+ }
78
+ function AsyncIterator(t, e) {
79
+ function invoke(r, o, i, a) {
80
+ var c = tryCatch(t[r], t, o);
81
+ if ("throw" !== c.type) {
82
+ var u = c.arg,
83
+ h = u.value;
84
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
85
+ invoke("next", t, i, a);
86
+ }, function (t) {
87
+ invoke("throw", t, i, a);
88
+ }) : e.resolve(h).then(function (t) {
89
+ u.value = t, i(u);
90
+ }, function (t) {
91
+ return invoke("throw", t, i, a);
92
+ });
93
+ }
94
+ a(c.arg);
95
+ }
96
+ var r;
97
+ o(this, "_invoke", {
98
+ value: function (t, n) {
99
+ function callInvokeWithMethodAndArg() {
100
+ return new e(function (e, r) {
101
+ invoke(t, n, e, r);
102
+ });
103
+ }
104
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
105
+ }
106
+ });
107
+ }
108
+ function makeInvokeMethod(e, r, n) {
109
+ var o = h;
110
+ return function (i, a) {
111
+ if (o === f) throw new Error("Generator is already running");
112
+ if (o === s) {
113
+ if ("throw" === i) throw a;
114
+ return {
115
+ value: t,
116
+ done: !0
117
+ };
118
+ }
119
+ for (n.method = i, n.arg = a;;) {
120
+ var c = n.delegate;
121
+ if (c) {
122
+ var u = maybeInvokeDelegate(c, n);
123
+ if (u) {
124
+ if (u === y) continue;
125
+ return u;
126
+ }
127
+ }
128
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
129
+ if (o === h) throw o = s, n.arg;
130
+ n.dispatchException(n.arg);
131
+ } else "return" === n.method && n.abrupt("return", n.arg);
132
+ o = f;
133
+ var p = tryCatch(e, r, n);
134
+ if ("normal" === p.type) {
135
+ if (o = n.done ? s : l, p.arg === y) continue;
136
+ return {
137
+ value: p.arg,
138
+ done: n.done
139
+ };
140
+ }
141
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
142
+ }
143
+ };
144
+ }
145
+ function maybeInvokeDelegate(e, r) {
146
+ var n = r.method,
147
+ o = e.iterator[n];
148
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
149
+ var i = tryCatch(o, e.iterator, r.arg);
150
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
151
+ var a = i.arg;
152
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
153
+ }
154
+ function pushTryEntry(t) {
155
+ var e = {
156
+ tryLoc: t[0]
157
+ };
158
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
159
+ }
160
+ function resetTryEntry(t) {
161
+ var e = t.completion || {};
162
+ e.type = "normal", delete e.arg, t.completion = e;
163
+ }
164
+ function Context(t) {
165
+ this.tryEntries = [{
166
+ tryLoc: "root"
167
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
168
+ }
169
+ function values(e) {
170
+ if (e || "" === e) {
171
+ var r = e[a];
172
+ if (r) return r.call(e);
173
+ if ("function" == typeof e.next) return e;
174
+ if (!isNaN(e.length)) {
175
+ var o = -1,
176
+ i = function next() {
177
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
178
+ return next.value = t, next.done = !0, next;
179
+ };
180
+ return i.next = i;
181
+ }
182
+ }
183
+ throw new TypeError(typeof e + " is not iterable");
184
+ }
185
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
186
+ value: GeneratorFunctionPrototype,
187
+ configurable: !0
188
+ }), o(GeneratorFunctionPrototype, "constructor", {
189
+ value: GeneratorFunction,
190
+ configurable: !0
191
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
192
+ var e = "function" == typeof t && t.constructor;
193
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
194
+ }, e.mark = function (t) {
195
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
196
+ }, e.awrap = function (t) {
197
+ return {
198
+ __await: t
199
+ };
200
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
201
+ return this;
202
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
203
+ void 0 === i && (i = Promise);
204
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
205
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
206
+ return t.done ? t.value : a.next();
207
+ });
208
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
209
+ return this;
210
+ }), define(g, "toString", function () {
211
+ return "[object Generator]";
212
+ }), e.keys = function (t) {
213
+ var e = Object(t),
214
+ r = [];
215
+ for (var n in e) r.push(n);
216
+ return r.reverse(), function next() {
217
+ for (; r.length;) {
218
+ var t = r.pop();
219
+ if (t in e) return next.value = t, next.done = !1, next;
220
+ }
221
+ return next.done = !0, next;
222
+ };
223
+ }, e.values = values, Context.prototype = {
224
+ constructor: Context,
225
+ reset: function (e) {
226
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
227
+ },
228
+ stop: function () {
229
+ this.done = !0;
230
+ var t = this.tryEntries[0].completion;
231
+ if ("throw" === t.type) throw t.arg;
232
+ return this.rval;
233
+ },
234
+ dispatchException: function (e) {
235
+ if (this.done) throw e;
236
+ var r = this;
237
+ function handle(n, o) {
238
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
239
+ }
240
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
241
+ var i = this.tryEntries[o],
242
+ a = i.completion;
243
+ if ("root" === i.tryLoc) return handle("end");
244
+ if (i.tryLoc <= this.prev) {
245
+ var c = n.call(i, "catchLoc"),
246
+ u = n.call(i, "finallyLoc");
247
+ if (c && u) {
248
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
249
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
250
+ } else if (c) {
251
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
252
+ } else {
253
+ if (!u) throw new Error("try statement without catch or finally");
254
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
255
+ }
256
+ }
257
+ }
258
+ },
259
+ abrupt: function (t, e) {
260
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
261
+ var o = this.tryEntries[r];
262
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
263
+ var i = o;
264
+ break;
265
+ }
266
+ }
267
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
268
+ var a = i ? i.completion : {};
269
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
270
+ },
271
+ complete: function (t, e) {
272
+ if ("throw" === t.type) throw t.arg;
273
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
274
+ },
275
+ finish: function (t) {
276
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
277
+ var r = this.tryEntries[e];
278
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
279
+ }
280
+ },
281
+ catch: function (t) {
282
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
283
+ var r = this.tryEntries[e];
284
+ if (r.tryLoc === t) {
285
+ var n = r.completion;
286
+ if ("throw" === n.type) {
287
+ var o = n.arg;
288
+ resetTryEntry(r);
289
+ }
290
+ return o;
291
+ }
292
+ }
293
+ throw new Error("illegal catch attempt");
294
+ },
295
+ delegateYield: function (e, r, n) {
296
+ return this.delegate = {
297
+ iterator: values(e),
298
+ resultName: r,
299
+ nextLoc: n
300
+ }, "next" === this.method && (this.arg = t), y;
301
+ }
302
+ }, e;
303
+ }
304
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
305
+ try {
306
+ var info = gen[key](arg);
307
+ var value = info.value;
308
+ } catch (error) {
309
+ reject(error);
310
+ return;
311
+ }
312
+ if (info.done) {
313
+ resolve(value);
314
+ } else {
315
+ Promise.resolve(value).then(_next, _throw);
316
+ }
317
+ }
318
+ function _asyncToGenerator(fn) {
319
+ return function () {
320
+ var self = this,
321
+ args = arguments;
322
+ return new Promise(function (resolve, reject) {
323
+ var gen = fn.apply(self, args);
324
+ function _next(value) {
325
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
326
+ }
327
+ function _throw(err) {
328
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
329
+ }
330
+ _next(undefined);
331
+ });
332
+ };
333
+ }
334
+
335
+ var fetch = /*#__PURE__*/require('node-fetch');
336
+ function getUser(_x, _x2) {
337
+ return _getUser.apply(this, arguments);
338
+ }
339
+ function _getUser() {
340
+ _getUser = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(token, domainName) {
341
+ var params, response, data;
342
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
343
+ while (1) switch (_context.prev = _context.next) {
344
+ case 0:
345
+ params = {
346
+ method: 'GET',
347
+ headers: {
348
+ Authorization: token,
349
+ 'Content-Type': 'application/json'
350
+ }
351
+ };
352
+ _context.next = 3;
353
+ return fetch("http://localhost:4012/api/v1/get-tenant-user/" + domainName, params);
354
+ case 3:
355
+ response = _context.sent;
356
+ _context.next = 6;
357
+ return response.json();
358
+ case 6:
359
+ data = _context.sent;
360
+ return _context.abrupt("return", {
361
+ response: response,
362
+ data: data
363
+ });
364
+ case 8:
365
+ case "end":
366
+ return _context.stop();
367
+ }
368
+ }, _callee);
369
+ }));
370
+ return _getUser.apply(this, arguments);
371
+ }
372
+
3
373
  var dauth = function dauth(_ref) {
4
- var ssid = _ref.ssid;
374
+ var ssid = _ref.ssid,
375
+ domainName = _ref.domainName;
5
376
  return function (req, res, next) {
6
377
  if (!req.headers.authorization) {
7
378
  return res.status(403).send({
@@ -11,22 +382,46 @@ var dauth = function dauth(_ref) {
11
382
  }
12
383
  var token = req.headers.authorization.replace(/['"]+/g, '');
13
384
  try {
14
- var payload = jwt.verify(token, ssid);
15
- req.user = payload;
16
- return next();
385
+ jwt.verify(token, ssid);
386
+ // req.user = payload;
387
+ getUser(token, domainName).then(function (getUserFetch) {
388
+ if (getUserFetch.response.status === 404) {
389
+ return res.status(404).send({
390
+ status: 'domain-not-found',
391
+ message: 'Dauth domain does not exist'
392
+ });
393
+ } else if (getUserFetch.response.status === 500) {
394
+ return res.status(500).send({
395
+ status: 'error',
396
+ message: 'Dauth server error'
397
+ });
398
+ } else if (getUserFetch.response.status === 200) {
399
+ req.user = getUserFetch.data.user;
400
+ // console.log('node-fetch npm', req.user);
401
+ return next();
402
+ } else {
403
+ return res.status(501).send({
404
+ status: 'error',
405
+ message: 'Dauth server error'
406
+ });
407
+ }
408
+ })["catch"](function (error) {
409
+ console.log('getDauthUser error', error);
410
+ return next();
411
+ });
17
412
  } catch (error) {
18
413
  if (error && (error == null ? void 0 : error.message) === 'jwt expired') {
19
414
  return res.status(500).send({
20
415
  status: 'token-expired',
21
416
  message: 'El token ha expirado',
22
- error: error,
417
+ // error: error,
23
418
  mdKey: 'ensure_auth'
24
419
  });
25
420
  }
26
421
  return res.status(500).send({
27
422
  status: 'token-invalid',
28
423
  message: 'El token no es válido',
29
- error: error,
424
+ // error: error,
30
425
  mdKey: 'ensure_auth'
31
426
  });
32
427
  }
@@ -1 +1 @@
1
- {"version":3,"file":"dauth-md-node.esm.js","sources":["../src/index.ts"],"sourcesContent":["import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid }: { ssid: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n const payload = jwt.verify(token, ssid as string) as IAccessToken;\n req.user = payload;\n return next();\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["dauth","_ref","ssid","req","res","next","headers","authorization","status","send","mdKey","token","replace","payload","jwt","verify","user","error","message"],"mappings":";;IAoCaA,KAAK,GAAG,SAARA,KAAKA,CAAAC,IAAA;MAAMC,IAAI,GAAAD,IAAA,CAAJC,IAAI;EAC1B,OAAO,UACLC,GAAiB,EACjBC,GAAoB,EACpBC,IAAkB;IAElB,IAAI,CAACF,GAAG,CAACG,OAAO,CAACC,aAAa,EAAE;MAC9B,OAAOH,GAAG,CACPI,MAAM,CAAC,GAAG,CAAC,CACXC,IAAI,CAAC;QAAED,MAAM,EAAE,iBAAiB;QAAEE,KAAK,EAAE;OAAe,CAAC;;IAE9D,IAAMC,KAAK,GAAGR,GAAG,CAACG,OAAO,CAACC,aAAa,CAACK,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC7D,IAAI;MACF,IAAMC,OAAO,GAAGC,GAAG,CAACC,MAAM,CAACJ,KAAK,EAAET,IAAc,CAAiB;MACjEC,GAAG,CAACa,IAAI,GAAGH,OAAO;MAClB,OAAOR,IAAI,EAAE;KACd,CAAC,OAAOY,KAAK,EAAE;MACd,IAAIA,KAAK,IAAI,CAAAA,KAAK,oBAALA,KAAK,CAAEC,OAAO,MAAK,aAAa,EAAE;QAC7C,OAAOd,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;UAC1BD,MAAM,EAAE,eAAe;UACvBU,OAAO,EAAE,sBAAsB;UAC/BD,KAAK,EAAEA,KAAK;UACZP,KAAK,EAAE;SACR,CAAC;;MAEJ,OAAON,GAAG,CAACI,MAAM,CAAC,GAAG,CAAC,CAACC,IAAI,CAAC;QAC1BD,MAAM,EAAE,eAAe;QACvBU,OAAO,EAAE,uBAAuB;QAChCD,KAAK,EAAEA,KAAK;QACZP,KAAK,EAAE;OACR,CAAC;;GAEL;AACH;;;;"}
1
+ {"version":3,"file":"dauth-md-node.esm.js","sources":["../src/api/dauth.api.ts","../src/index.ts"],"sourcesContent":["const fetch = require('node-fetch');\n\nexport async function getUser(token: string, domainName: string) {\n const params = {\n method: 'GET',\n headers: {\n Authorization: token,\n 'Content-Type': 'application/json',\n },\n };\n const response = await fetch(\n `http://localhost:4012/api/v1/get-tenant-user/${domainName}`,\n params\n );\n const data = await response.json();\n return { response, data };\n}","import {\n Request,\n NextFunction,\n Response as ExpressResponse,\n Handler,\n} from 'express';\nimport mongoose from 'mongoose';\nimport jwt from 'jsonwebtoken';\nimport { getUser } from './api/dauth.api';\n\nexport interface IAccessToken {\n _id: string | mongoose.Types.ObjectId;\n sid: string;\n name: string;\n lastname: string;\n email: string;\n createToken?: number;\n exp?: number;\n iat?: number;\n}\n\ninterface IRequestUser extends Request {\n user: IAccessToken;\n files: {\n image: { path: string };\n avatar: { path: string };\n };\n headers: {\n authorization: string;\n };\n}\n\ninterface TCustomResponse extends ExpressResponse {\n status(code: number): any;\n send(body?: any): any;\n}\n\nexport const dauth = ({ ssid, domainName }: { ssid: string, domainName: string }) => {\n return (\n req: IRequestUser,\n res: TCustomResponse,\n next: NextFunction\n ): Handler | void => {\n if (!req.headers.authorization) {\n return res\n .status(403)\n .send({ status: 'token-not-found', mdKey: 'ensure_auth' });\n }\n const token = req.headers.authorization.replace(/['\"]+/g, '');\n try {\n jwt.verify(token, ssid as string) as IAccessToken;\n // req.user = payload;\n getUser(token, domainName)\n .then((getUserFetch: any) => {\n if (getUserFetch.response.status === 404) {\n return res.status(404).send({\n status: 'domain-not-found',\n message: 'Dauth domain does not exist',\n });\n } else if (getUserFetch.response.status === 500) {\n return res\n .status(500)\n .send({ status: 'error', message: 'Dauth server error' });\n } else if (getUserFetch.response.status === 200) {\n req.user = getUserFetch.data.user;\n // console.log('node-fetch npm', req.user);\n return next();\n } else {\n return res.status(501).send({\n status: 'error',\n message: 'Dauth server error',\n });\n }\n })\n .catch((error: any) => {\n console.log('getDauthUser error', error);\n return next();\n });\n } catch (error) {\n if (error && error?.message === 'jwt expired') {\n return res.status(500).send({\n status: 'token-expired',\n message: 'El token ha expirado',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n return res.status(500).send({\n status: 'token-invalid',\n message: 'El token no es válido',\n // error: error,\n mdKey: 'ensure_auth',\n });\n }\n };\n};\n"],"names":["fetch","require","getUser","_x","_x2","_getUser","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","token","domainName","params","response","data","wrap","_callee$","_context","prev","next","method","headers","Authorization","sent","json","abrupt","stop","dauth","_ref","ssid","req","res","authorization","status","send","mdKey","replace","jwt","verify","then","getUserFetch","message","user","error","console","log"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAMA,KAAK,gBAAGC,OAAO,CAAC,YAAY,CAAC;SAEbC,OAAOA,CAAAC,EAAA,EAAAC,GAAA;EAAA,OAAAC,QAAA,CAAAC,KAAA,OAAAC,SAAA;AAAA;AAc5B,SAAAF;EAAAA,QAAA,GAAAG,iBAAA,eAAAC,mBAAA,GAAAC,IAAA,CAdM,SAAAC,QAAuBC,KAAa,EAAEC,UAAkB;IAAA,IAAAC,MAAA,EAAAC,QAAA,EAAAC,IAAA;IAAA,OAAAP,mBAAA,GAAAQ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,MAAM,EAAE,eAAe;QACvBQ,OAAO,EAAE,uBAAuB;;QAEhCN,KAAK,EAAE;OACR,CAAC;;GAEL;AACH,CAAC;;;;"}
package/dist/index.d.ts CHANGED
@@ -28,7 +28,8 @@ interface TCustomResponse extends ExpressResponse {
28
28
  status(code: number): any;
29
29
  send(body?: any): any;
30
30
  }
31
- export declare const dauth: ({ ssid }: {
31
+ export declare const dauth: ({ ssid, domainName }: {
32
32
  ssid: string;
33
+ domainName: string;
33
34
  }) => (req: IRequestUser, res: TCustomResponse, next: NextFunction) => Handler | void;
34
35
  export {};
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.71",
2
+ "version": "0.1.73",
3
3
  "license": "MIT",
4
4
  "main": "dist/index.js",
5
5
  "typings": "dist/index.d.ts",
@@ -47,6 +47,7 @@
47
47
  "@size-limit/preset-small-lib": "^11.0.2",
48
48
  "@types/express": "^4.17.21",
49
49
  "@types/jsonwebtoken": "^9.0.5",
50
+ "@types/node-fetch": "^2.6.11",
50
51
  "husky": "^9.0.11",
51
52
  "size-limit": "^11.0.2",
52
53
  "tsdx": "^0.14.1",
@@ -56,6 +57,7 @@
56
57
  "dependencies": {
57
58
  "express": "^4.18.2",
58
59
  "jsonwebtoken": "^9.0.2",
59
- "mongoose": "^8.1.2"
60
+ "mongoose": "^8.1.2",
61
+ "node-fetch": "^2.6.1"
60
62
  }
61
63
  }
@@ -0,0 +1,17 @@
1
+ const fetch = require('node-fetch');
2
+
3
+ export async function getUser(token: string, domainName: string) {
4
+ const params = {
5
+ method: 'GET',
6
+ headers: {
7
+ Authorization: token,
8
+ 'Content-Type': 'application/json',
9
+ },
10
+ };
11
+ const response = await fetch(
12
+ `http://localhost:4012/api/v1/get-tenant-user/${domainName}`,
13
+ params
14
+ );
15
+ const data = await response.json();
16
+ return { response, data };
17
+ }
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  } from 'express';
7
7
  import mongoose from 'mongoose';
8
8
  import jwt from 'jsonwebtoken';
9
+ import { getUser } from './api/dauth.api';
9
10
 
10
11
  export interface IAccessToken {
11
12
  _id: string | mongoose.Types.ObjectId;
@@ -34,7 +35,7 @@ interface TCustomResponse extends ExpressResponse {
34
35
  send(body?: any): any;
35
36
  }
36
37
 
37
- export const dauth = ({ ssid }: { ssid: string }) => {
38
+ export const dauth = ({ ssid, domainName }: { ssid: string, domainName: string }) => {
38
39
  return (
39
40
  req: IRequestUser,
40
41
  res: TCustomResponse,
@@ -47,22 +48,47 @@ export const dauth = ({ ssid }: { ssid: string }) => {
47
48
  }
48
49
  const token = req.headers.authorization.replace(/['"]+/g, '');
49
50
  try {
50
- const payload = jwt.verify(token, ssid as string) as IAccessToken;
51
- req.user = payload;
52
- return next();
51
+ jwt.verify(token, ssid as string) as IAccessToken;
52
+ // req.user = payload;
53
+ getUser(token, domainName)
54
+ .then((getUserFetch: any) => {
55
+ if (getUserFetch.response.status === 404) {
56
+ return res.status(404).send({
57
+ status: 'domain-not-found',
58
+ message: 'Dauth domain does not exist',
59
+ });
60
+ } else if (getUserFetch.response.status === 500) {
61
+ return res
62
+ .status(500)
63
+ .send({ status: 'error', message: 'Dauth server error' });
64
+ } else if (getUserFetch.response.status === 200) {
65
+ req.user = getUserFetch.data.user;
66
+ // console.log('node-fetch npm', req.user);
67
+ return next();
68
+ } else {
69
+ return res.status(501).send({
70
+ status: 'error',
71
+ message: 'Dauth server error',
72
+ });
73
+ }
74
+ })
75
+ .catch((error: any) => {
76
+ console.log('getDauthUser error', error);
77
+ return next();
78
+ });
53
79
  } catch (error) {
54
80
  if (error && error?.message === 'jwt expired') {
55
81
  return res.status(500).send({
56
82
  status: 'token-expired',
57
83
  message: 'El token ha expirado',
58
- error: error,
84
+ // error: error,
59
85
  mdKey: 'ensure_auth',
60
86
  });
61
87
  }
62
88
  return res.status(500).send({
63
89
  status: 'token-invalid',
64
90
  message: 'El token no es válido',
65
- error: error,
91
+ // error: error,
66
92
  mdKey: 'ensure_auth',
67
93
  });
68
94
  }