@nocobase/plugin-auth 1.6.0-alpha.3 → 1.6.0-alpha.30

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.
Files changed (42) hide show
  1. package/dist/client/{0994a09f2c3ca18d.js → 0091d4359312cb07.js} +1 -1
  2. package/dist/client/{1c5e32ff8bef5e4a.js → 974ac9de644a1d1f.js} +1 -1
  3. package/dist/client/{6992b2fd9b0275b1.js → 9e603524b127e7b4.js} +1 -1
  4. package/dist/client/f2122264b5758d8b.js +10 -0
  5. package/dist/client/index.d.ts +5 -6
  6. package/dist/client/index.js +1 -1
  7. package/dist/client/interceptors.d.ts +13 -0
  8. package/dist/client/settings/token-policy/components.d.ts +15 -0
  9. package/dist/client/settings/token-policy/hooks.d.ts +24 -0
  10. package/dist/client/settings/token-policy/index.d.ts +10 -0
  11. package/dist/constants.d.ts +13 -0
  12. package/dist/constants.js +48 -0
  13. package/dist/externalVersion.js +13 -10
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +4 -2
  16. package/dist/locale/en-US.json +18 -1
  17. package/dist/locale/zh-CN.json +17 -1
  18. package/dist/node_modules/cron/package.json +1 -1
  19. package/dist/node_modules/ms/index.js +1 -0
  20. package/dist/node_modules/ms/package.json +1 -0
  21. package/dist/server/actions/auth.js +14 -3
  22. package/dist/server/basic-auth.js +4 -1
  23. package/dist/server/collections/authenticators.js +1 -0
  24. package/dist/server/collections/issued-tokens.d.ts +10 -0
  25. package/dist/server/collections/issued-tokens.js +70 -0
  26. package/dist/server/collections/token-blacklist.js +1 -0
  27. package/dist/server/collections/token-poilcy-config.d.ts +10 -0
  28. package/dist/server/collections/token-poilcy-config.js +57 -0
  29. package/dist/server/collections/users-authenticators.js +1 -0
  30. package/dist/server/index.d.ts +2 -0
  31. package/dist/server/index.js +8 -2
  32. package/dist/server/migrations/20241229080941-create-token-policy-config.d.ts +14 -0
  33. package/dist/server/migrations/20241229080941-create-token-policy-config.js +58 -0
  34. package/dist/server/plugin.js +112 -54
  35. package/dist/server/storer.d.ts +8 -2
  36. package/dist/server/storer.js +28 -3
  37. package/dist/server/token-blacklist.js +13 -2
  38. package/dist/server/token-controller.d.ts +40 -0
  39. package/dist/server/token-controller.js +152 -0
  40. package/dist/types.d.ts +9 -0
  41. package/dist/types.js +24 -0
  42. package/package.json +5 -3
@@ -1 +1 @@
1
- {"name":"cron","description":"Cron jobs for your node","version":"2.4.4","author":"Nick Campbell <nicholas.j.campbell@gmail.com> (https://github.com/ncb000gt)","bugs":{"url":"https://github.com/kelektiv/node-cron/issues"},"repository":{"type":"git","url":"https://github.com/kelektiv/node-cron.git"},"main":"lib/cron","scripts":{"lint":"eslint {lib,tests}/*.js","test":"jest --coverage","test:watch":"jest --watch --coverage","test:types":"tsd","prepare":"husky install","release":"semantic-release"},"types":"types/index.d.ts","dependencies":{"@types/luxon":"~3.3.0","luxon":"~3.3.0"},"devDependencies":{"@commitlint/cli":"~17.6.6","@insurgentlab/commitlint-config":"^18.1.0","@insurgentlab/conventional-changelog-preset":"~6.0.3","@semantic-release/changelog":"~6.0.x","@semantic-release/commit-analyzer":"~9.0.x","@semantic-release/git":"~10.0.x","@semantic-release/github":"~8.1.x","@semantic-release/npm":"~10.0.x","@semantic-release/release-notes-generator":"~11.0.x","chai":"~4.2.x","eslint":"~8.36.x","eslint-config-prettier":"^8.7.x","eslint-config-standard":"~17.0.x","eslint-plugin-import":"~2.27.x","eslint-plugin-jest":"~27.2.x","eslint-plugin-n":"~15.6.x","eslint-plugin-prettier":"~4.2.x","eslint-plugin-promise":"~6.1.x","husky":"^8.0.3","jest":"~29.5.x","prettier":"~2.8.x","semantic-release":"~21.0.x","sinon":"^15.0.x","tsd":"^0.28.1"},"keywords":["cron","node cron","node-cron","schedule","scheduler","cronjob","cron job"],"license":"MIT","contributors":["Brandon der Blätter <https://interlucid.com/contact/> (https://github.com/intcreator)","Romain Beauxis <toots@rastageeks.org> (https://github.com/toots)","James Padolsey <> (https://github.com/jamespadolsey)","Finn Herpich <fh@three-heads.de> (https://github.com/ErrorProne)","Clifton Cunningham <clifton.cunningham@gmail.com> (https://github.com/cliftonc)","Eric Abouaf <eric.abouaf@gmail.com> (https://github.com/neyric)","humanchimp <morphcham@gmail.com> (https://github.com/humanchimp)","Craig Condon <craig@spiceapps.com> (https://github.com/spiceapps)","Dan Bear <daniel@hulu.com> (https://github.com/danhbear)","Vadim Baryshev <vadimbaryshev@gmail.com> (https://github.com/baryshev)","Leandro Ferrari <lfthomaz@gmail.com> (https://github.com/lfthomaz)","Gregg Zigler <greggzigler@gmail.com> (https://github.com/greggzigler)","Jordan Abderrachid <jabderrachid@gmail.com> (https://github.com/jordanabderrachid)","Masakazu Matsushita <matsukaz@gmail.com> (matsukaz)","Christopher Lunt <me@kirisu.co.uk> (https://github.com/kirisu)"],"jest":{"collectCoverage":true,"collectCoverageFrom":["lib/*.js"],"coverageThreshold":{"global":{"statements":80,"branches":80,"functions":70,"lines":80}}},"files":["lib","types","CHANGELOG.md","LICENSE","README.md"],"_lastModified":"2024-12-09T02:48:56.427Z"}
1
+ {"name":"cron","description":"Cron jobs for your node","version":"2.4.4","author":"Nick Campbell <nicholas.j.campbell@gmail.com> (https://github.com/ncb000gt)","bugs":{"url":"https://github.com/kelektiv/node-cron/issues"},"repository":{"type":"git","url":"https://github.com/kelektiv/node-cron.git"},"main":"lib/cron","scripts":{"lint":"eslint {lib,tests}/*.js","test":"jest --coverage","test:watch":"jest --watch --coverage","test:types":"tsd","prepare":"husky install","release":"semantic-release"},"types":"types/index.d.ts","dependencies":{"@types/luxon":"~3.3.0","luxon":"~3.3.0"},"devDependencies":{"@commitlint/cli":"~17.6.6","@insurgentlab/commitlint-config":"^18.1.0","@insurgentlab/conventional-changelog-preset":"~6.0.3","@semantic-release/changelog":"~6.0.x","@semantic-release/commit-analyzer":"~9.0.x","@semantic-release/git":"~10.0.x","@semantic-release/github":"~8.1.x","@semantic-release/npm":"~10.0.x","@semantic-release/release-notes-generator":"~11.0.x","chai":"~4.2.x","eslint":"~8.36.x","eslint-config-prettier":"^8.7.x","eslint-config-standard":"~17.0.x","eslint-plugin-import":"~2.27.x","eslint-plugin-jest":"~27.2.x","eslint-plugin-n":"~15.6.x","eslint-plugin-prettier":"~4.2.x","eslint-plugin-promise":"~6.1.x","husky":"^8.0.3","jest":"~29.5.x","prettier":"~2.8.x","semantic-release":"~21.0.x","sinon":"^15.0.x","tsd":"^0.28.1"},"keywords":["cron","node cron","node-cron","schedule","scheduler","cronjob","cron job"],"license":"MIT","contributors":["Brandon der Blätter <https://interlucid.com/contact/> (https://github.com/intcreator)","Romain Beauxis <toots@rastageeks.org> (https://github.com/toots)","James Padolsey <> (https://github.com/jamespadolsey)","Finn Herpich <fh@three-heads.de> (https://github.com/ErrorProne)","Clifton Cunningham <clifton.cunningham@gmail.com> (https://github.com/cliftonc)","Eric Abouaf <eric.abouaf@gmail.com> (https://github.com/neyric)","humanchimp <morphcham@gmail.com> (https://github.com/humanchimp)","Craig Condon <craig@spiceapps.com> (https://github.com/spiceapps)","Dan Bear <daniel@hulu.com> (https://github.com/danhbear)","Vadim Baryshev <vadimbaryshev@gmail.com> (https://github.com/baryshev)","Leandro Ferrari <lfthomaz@gmail.com> (https://github.com/lfthomaz)","Gregg Zigler <greggzigler@gmail.com> (https://github.com/greggzigler)","Jordan Abderrachid <jabderrachid@gmail.com> (https://github.com/jordanabderrachid)","Masakazu Matsushita <matsukaz@gmail.com> (matsukaz)","Christopher Lunt <me@kirisu.co.uk> (https://github.com/kirisu)"],"jest":{"collectCoverage":true,"collectCoverageFrom":["lib/*.js"],"coverageThreshold":{"global":{"statements":80,"branches":80,"functions":70,"lines":80}}},"files":["lib","types","CHANGELOG.md","LICENSE","README.md"],"_lastModified":"2025-03-07T08:30:20.403Z"}
@@ -0,0 +1 @@
1
+ (function(){var e={900:function(e){var r=1e3;var s=r*60;var a=s*60;var n=a*24;var t=n*7;var u=n*365.25;e.exports=function(e,r){r=r||{};var s=typeof e;if(s==="string"&&e.length>0){return parse(e)}else if(s==="number"&&isFinite(e)){return r.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var c=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!c){return}var i=parseFloat(c[1]);var o=(c[2]||"ms").toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*u;case"weeks":case"week":case"w":return i*t;case"days":case"day":case"d":return i*n;case"hours":case"hour":case"hrs":case"hr":case"h":return i*a;case"minutes":case"minute":case"mins":case"min":case"m":return i*s;case"seconds":case"second":case"secs":case"sec":case"s":return i*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return undefined}}function fmtShort(e){var t=Math.abs(e);if(t>=n){return Math.round(e/n)+"d"}if(t>=a){return Math.round(e/a)+"h"}if(t>=s){return Math.round(e/s)+"m"}if(t>=r){return Math.round(e/r)+"s"}return e+"ms"}function fmtLong(e){var t=Math.abs(e);if(t>=n){return plural(e,t,n,"day")}if(t>=a){return plural(e,t,a,"hour")}if(t>=s){return plural(e,t,s,"minute")}if(t>=r){return plural(e,t,r,"second")}return e+" ms"}function plural(e,r,s,a){var n=r>=s*1.5;return Math.round(e/s)+" "+a+(n?"s":"")}}};var r={};function __nccwpck_require__(s){var a=r[s];if(a!==undefined){return a.exports}var n=r[s]={exports:{}};var t=true;try{e[s](n,n.exports,__nccwpck_require__);t=false}finally{if(t)delete r[s]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(900);module.exports=s})();
@@ -0,0 +1 @@
1
+ {"name":"ms","version":"2.1.3","description":"Tiny millisecond conversion utility","repository":"vercel/ms","main":"./index","files":["index.js"],"scripts":{"precommit":"lint-staged","lint":"eslint lib/* bin/*","test":"mocha tests.js"},"eslintConfig":{"extends":"eslint:recommended","env":{"node":true,"es6":true}},"lint-staged":{"*.js":["npm run lint","prettier --single-quote --write","git add"]},"license":"MIT","devDependencies":{"eslint":"4.18.2","expect.js":"0.3.1","husky":"0.14.3","lint-staged":"5.0.0","mocha":"4.0.1","prettier":"2.0.5"},"_lastModified":"2025-03-07T08:30:20.491Z"}
@@ -45,6 +45,12 @@ var auth_default = {
45
45
  // await next();
46
46
  // },
47
47
  changePassword: async (ctx, next) => {
48
+ const systemSettings = ctx.db.getRepository("systemSettings");
49
+ const settings = await systemSettings.findOne();
50
+ const enableChangePassword = settings.get("enableChangePassword");
51
+ if (enableChangePassword === false) {
52
+ ctx.throw(403, ctx.t("Password is not allowed to be changed", { ns: import_preset.namespace }));
53
+ }
48
54
  const {
49
55
  values: { oldPassword, newPassword, confirmPassword }
50
56
  } = ctx.action.params;
@@ -61,7 +67,8 @@ var auth_default = {
61
67
  } else {
62
68
  key = "email";
63
69
  }
64
- const user = await ctx.db.getRepository("users").findOne({
70
+ const UserRepo = ctx.db.getRepository("users");
71
+ const user = await UserRepo.findOne({
65
72
  where: {
66
73
  [key]: currentUser[key]
67
74
  }
@@ -71,8 +78,12 @@ var auth_default = {
71
78
  if (!isValid) {
72
79
  ctx.throw(401, ctx.t("The password is incorrect, please re-enter", { ns: import_preset.namespace }));
73
80
  }
74
- user.password = newPassword;
75
- await user.save();
81
+ await UserRepo.update({
82
+ filterByTk: user.id,
83
+ values: {
84
+ password: newPassword
85
+ }
86
+ });
76
87
  ctx.body = currentUser;
77
88
  await next();
78
89
  }
@@ -72,7 +72,10 @@ class BasicAuth extends import_auth.BaseAuth {
72
72
  const field = this.userCollection.getField("password");
73
73
  const valid = await field.verify(password, user.password);
74
74
  if (!valid) {
75
- ctx.throw(401, ctx.t("The username/email or password is incorrect, please re-enter", { ns: import_preset.namespace }));
75
+ ctx.throw(401, ctx.t("The username/email or password is incorrect, please re-enter", { ns: import_preset.namespace }), {
76
+ code: "INCORRECT_PASSWORD",
77
+ user
78
+ });
76
79
  }
77
80
  return user;
78
81
  }
@@ -34,6 +34,7 @@ var authenticators_default = (0, import_database.defineCollection)({
34
34
  dumpRules: {
35
35
  group: "third-party"
36
36
  },
37
+ migrationRules: ["overwrite", "schema-only"],
37
38
  shared: true,
38
39
  name: "authenticators",
39
40
  sortable: true,
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ declare const _default: import("@nocobase/database").CollectionOptions;
10
+ export default _default;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var issued_tokens_exports = {};
28
+ __export(issued_tokens_exports, {
29
+ default: () => issued_tokens_default
30
+ });
31
+ module.exports = __toCommonJS(issued_tokens_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_constants = require("../../constants");
34
+ var issued_tokens_default = (0, import_database.defineCollection)({
35
+ name: import_constants.issuedTokensCollectionName,
36
+ migrationRules: ["schema-only"],
37
+ autoGenId: false,
38
+ createdAt: true,
39
+ updatedAt: true,
40
+ fields: [
41
+ {
42
+ name: "id",
43
+ type: "uuid",
44
+ primaryKey: true,
45
+ allowNull: false,
46
+ interface: "input"
47
+ },
48
+ {
49
+ type: "bigInt",
50
+ name: "signInTime",
51
+ allowNull: false
52
+ },
53
+ {
54
+ name: "jti",
55
+ type: "uuid",
56
+ allowNull: false,
57
+ index: true
58
+ },
59
+ {
60
+ type: "bigInt",
61
+ name: "issuedTime",
62
+ allowNull: false
63
+ },
64
+ {
65
+ type: "bigInt",
66
+ name: "userId",
67
+ allowNull: false
68
+ }
69
+ ]
70
+ });
@@ -34,6 +34,7 @@ var token_blacklist_default = (0, import_database.defineCollection)({
34
34
  dumpRules: {
35
35
  group: "log"
36
36
  },
37
+ migrationRules: ["schema-only"],
37
38
  shared: true,
38
39
  name: "tokenBlacklist",
39
40
  model: "TokenBlacklistModel",
@@ -0,0 +1,10 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ declare const _default: import("@nocobase/database").CollectionOptions;
10
+ export default _default;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var token_poilcy_config_exports = {};
28
+ __export(token_poilcy_config_exports, {
29
+ default: () => token_poilcy_config_default
30
+ });
31
+ module.exports = __toCommonJS(token_poilcy_config_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_constants = require("../../constants");
34
+ var token_poilcy_config_default = (0, import_database.defineCollection)({
35
+ name: import_constants.tokenPolicyCollectionName,
36
+ migrationRules: ["overwrite", "schema-only"],
37
+ autoGenId: false,
38
+ createdAt: true,
39
+ createdBy: true,
40
+ updatedAt: true,
41
+ updatedBy: true,
42
+ fields: [
43
+ {
44
+ name: "key",
45
+ type: "string",
46
+ primaryKey: true,
47
+ allowNull: false,
48
+ interface: "input"
49
+ },
50
+ {
51
+ type: "json",
52
+ name: "config",
53
+ allowNull: false,
54
+ defaultValue: {}
55
+ }
56
+ ]
57
+ });
@@ -35,6 +35,7 @@ var users_authenticators_default = (0, import_database.defineCollection)({
35
35
  group: "user"
36
36
  },
37
37
  shared: true,
38
+ migrationRules: ["schema-only", "overwrite"],
38
39
  name: "usersAuthenticators",
39
40
  model: "UserAuthModel",
40
41
  createdBy: true,
@@ -8,4 +8,6 @@
8
8
  */
9
9
  export { BasicAuth } from './basic-auth';
10
10
  export { AuthModel } from './model/authenticator';
11
+ export { presetAuthType } from '../preset';
11
12
  export { default } from './plugin';
13
+ export * from '../constants';
@@ -25,6 +25,7 @@ var __copyProps = (to, from, except, desc) => {
25
25
  }
26
26
  return to;
27
27
  };
28
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
28
29
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
30
  // If the importer is in node compatibility mode or this is not an ESM
30
31
  // file that has been converted to a CommonJS file using a Babel-
@@ -38,14 +39,19 @@ var server_exports = {};
38
39
  __export(server_exports, {
39
40
  AuthModel: () => import_authenticator.AuthModel,
40
41
  BasicAuth: () => import_basic_auth.BasicAuth,
41
- default: () => import_plugin.default
42
+ default: () => import_plugin.default,
43
+ presetAuthType: () => import_preset.presetAuthType
42
44
  });
43
45
  module.exports = __toCommonJS(server_exports);
44
46
  var import_basic_auth = require("./basic-auth");
45
47
  var import_authenticator = require("./model/authenticator");
48
+ var import_preset = require("../preset");
46
49
  var import_plugin = __toESM(require("./plugin"));
50
+ __reExport(server_exports, require("../constants"), module.exports);
47
51
  // Annotate the CommonJS export names for ESM import in node:
48
52
  0 && (module.exports = {
49
53
  AuthModel,
50
- BasicAuth
54
+ BasicAuth,
55
+ presetAuthType,
56
+ ...require("../constants")
51
57
  });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { Migration } from '@nocobase/server';
10
+ export default class extends Migration {
11
+ on: string;
12
+ appVersion: string;
13
+ up(): Promise<void>;
14
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var create_token_policy_config_exports = {};
28
+ __export(create_token_policy_config_exports, {
29
+ default: () => create_token_policy_config_default
30
+ });
31
+ module.exports = __toCommonJS(create_token_policy_config_exports);
32
+ var import_server = require("@nocobase/server");
33
+ var import_constants = require("../../constants");
34
+ class create_token_policy_config_default extends import_server.Migration {
35
+ on = "afterLoad";
36
+ // 'beforeLoad' or 'afterLoad'
37
+ appVersion = "<1.6.1";
38
+ async up() {
39
+ const tokenPolicyRepo = this.app.db.getRepository(import_constants.tokenPolicyCollectionName);
40
+ const tokenPolicy = await tokenPolicyRepo.findOne({ filterByTk: import_constants.tokenPolicyRecordKey });
41
+ if (tokenPolicy) {
42
+ this.app.authManager.tokenController.setConfig(tokenPolicy.config);
43
+ } else {
44
+ const config = {
45
+ tokenExpirationTime: "1d",
46
+ sessionExpirationTime: "7d",
47
+ expiredTokenRenewLimit: "1d"
48
+ };
49
+ await tokenPolicyRepo.create({
50
+ values: {
51
+ key: import_constants.tokenPolicyRecordKey,
52
+ config
53
+ }
54
+ });
55
+ this.app.authManager.tokenController.setConfig(config);
56
+ }
57
+ }
58
+ }
@@ -41,6 +41,7 @@ __export(plugin_exports, {
41
41
  });
42
42
  module.exports = __toCommonJS(plugin_exports);
43
43
  var import_server = require("@nocobase/server");
44
+ var import_utils = require("@nocobase/utils");
44
45
  var import_preset = require("../preset");
45
46
  var import_auth = __toESM(require("./actions/auth"));
46
47
  var import_authenticators = __toESM(require("./actions/authenticators"));
@@ -48,10 +49,31 @@ var import_basic_auth = require("./basic-auth");
48
49
  var import_authenticator = require("./model/authenticator");
49
50
  var import_storer = require("./storer");
50
51
  var import_token_blacklist = require("./token-blacklist");
51
- var import_utils = require("@nocobase/utils");
52
+ var import_token_controller = require("./token-controller");
53
+ var import_constants = require("../constants");
52
54
  class PluginAuthServer extends import_server.Plugin {
53
55
  cache;
54
56
  afterAdd() {
57
+ this.app.on("afterLoad", async () => {
58
+ if (this.app.authManager.tokenController) {
59
+ return;
60
+ }
61
+ const cache = await this.app.cacheManager.createCache({
62
+ name: "auth-token-controller",
63
+ prefix: "auth-token-controller"
64
+ });
65
+ const tokenController = new import_token_controller.TokenController({ cache, app: this.app, logger: this.app.log });
66
+ this.app.authManager.setTokenControlService(tokenController);
67
+ const tokenPolicyRepo = this.app.db.getRepository(import_constants.tokenPolicyCollectionName);
68
+ try {
69
+ const res = await tokenPolicyRepo.findOne({ filterByTk: import_constants.tokenPolicyRecordKey });
70
+ if (res) {
71
+ this.app.authManager.tokenController.setConfig(res.config);
72
+ }
73
+ } catch (error) {
74
+ this.app.logger.warn("access control config not exist, use default value");
75
+ }
76
+ });
55
77
  }
56
78
  async beforeLoad() {
57
79
  this.app.db.registerModels({ AuthModel: import_authenticator.AuthModel });
@@ -63,8 +85,10 @@ class PluginAuthServer extends import_server.Plugin {
63
85
  store: "memory"
64
86
  });
65
87
  const storer = new import_storer.Storer({
88
+ app: this.app,
66
89
  db: this.db,
67
- cache: this.cache
90
+ cache: this.cache,
91
+ authManager: this.app.authManager
68
92
  });
69
93
  this.app.authManager.setStorer(storer);
70
94
  if (!this.app.authManager.jwt.blacklist) {
@@ -109,8 +133,8 @@ class PluginAuthServer extends import_server.Plugin {
109
133
  Object.entries(import_authenticators.default).forEach(
110
134
  ([action, handler]) => this.app.resourceManager.registerActionHandler(`authenticators:${action}`, handler)
111
135
  );
112
- ["check", "signIn", "signUp"].forEach((action) => this.app.acl.allow("auth", action));
113
- ["signOut", "changePassword"].forEach((action) => this.app.acl.allow("auth", action, "loggedIn"));
136
+ ["signIn", "signUp"].forEach((action) => this.app.acl.allow("auth", action));
137
+ ["check", "signOut", "changePassword"].forEach((action) => this.app.acl.allow("auth", action, "loggedIn"));
114
138
  this.app.acl.allow("authenticators", "publicList");
115
139
  this.app.acl.registerSnippet({
116
140
  name: `pm.${this.name}.authenticators`,
@@ -127,11 +151,54 @@ class PluginAuthServer extends import_server.Plugin {
127
151
  this.app.on("cache:del:auth", async ({ userId }) => {
128
152
  await this.cache.del(`auth:${userId}`);
129
153
  });
154
+ this.app.on("ws:message:auth:token", async ({ clientId, payload }) => {
155
+ if (!payload || !payload.token || !payload.authenticator) {
156
+ this.app.emit(`ws:removeTag`, {
157
+ clientId,
158
+ tagKey: "userId"
159
+ });
160
+ return;
161
+ }
162
+ const auth = await this.app.authManager.get(payload.authenticator, {
163
+ getBearerToken: () => payload.token,
164
+ app: this.app,
165
+ db: this.app.db,
166
+ cache: this.app.cache,
167
+ logger: this.app.logger,
168
+ log: this.app.log,
169
+ throw: (...args) => {
170
+ throw new Error(...args);
171
+ },
172
+ t: this.app.i18n.t
173
+ });
174
+ let user;
175
+ try {
176
+ user = (await auth.checkToken()).user;
177
+ } catch (error) {
178
+ if (!user) {
179
+ this.app.logger.error(error);
180
+ this.app.emit(`ws:removeTag`, {
181
+ clientId,
182
+ tagKey: "userId"
183
+ });
184
+ return;
185
+ }
186
+ }
187
+ this.app.emit(`ws:setTag`, {
188
+ clientId,
189
+ tagKey: "userId",
190
+ tagValue: user.id
191
+ });
192
+ this.app.emit(`ws:authorized`, {
193
+ clientId,
194
+ userId: user.id
195
+ });
196
+ });
130
197
  this.app.auditManager.registerActions([
131
198
  {
132
199
  name: "auth:signIn",
133
200
  getMetaData: async (ctx) => {
134
- var _a, _b, _c, _d, _e, _f;
201
+ var _a;
135
202
  let body = {};
136
203
  if (ctx.status === 200) {
137
204
  body = {
@@ -145,20 +212,10 @@ class PluginAuthServer extends import_server.Plugin {
145
212
  }
146
213
  return {
147
214
  request: {
148
- params: (_a = ctx.request) == null ? void 0 : _a.params,
149
215
  body: {
150
- ...(_b = ctx.request) == null ? void 0 : _b.body,
216
+ ...(_a = ctx.request) == null ? void 0 : _a.body,
151
217
  password: void 0
152
- },
153
- path: (_c = ctx.request) == null ? void 0 : _c.path,
154
- headers: {
155
- "x-authenticator": (_d = ctx.request) == null ? void 0 : _d.headers["x-authenticator"],
156
- "x-locale": (_e = ctx.request) == null ? void 0 : _e.headers["x-locale"],
157
- "x-timezone": (_f = ctx.request) == null ? void 0 : _f.headers["x-timezone"]
158
218
  }
159
- },
160
- response: {
161
- body
162
219
  }
163
220
  };
164
221
  },
@@ -193,26 +250,13 @@ class PluginAuthServer extends import_server.Plugin {
193
250
  {
194
251
  name: "auth:signUp",
195
252
  getMetaData: async (ctx) => {
196
- var _a, _b, _c, _d, _e, _f, _g;
253
+ var _a;
197
254
  return {
198
255
  request: {
199
- params: (_a = ctx.request) == null ? void 0 : _a.params,
200
256
  body: {
201
- ...(_b = ctx.request) == null ? void 0 : _b.body,
257
+ ...(_a = ctx.request) == null ? void 0 : _a.body,
202
258
  password: void 0,
203
259
  confirm_password: void 0
204
- },
205
- path: (_c = ctx.request) == null ? void 0 : _c.path,
206
- headers: {
207
- "x-authenticator": (_d = ctx.request) == null ? void 0 : _d.headers["x-authenticator"],
208
- "x-locale": (_e = ctx.request) == null ? void 0 : _e.headers["x-locale"],
209
- "x-timezone": (_f = ctx.request) == null ? void 0 : _f.headers["x-timezone"]
210
- }
211
- },
212
- response: {
213
- body: {
214
- ...(_g = ctx.response) == null ? void 0 : _g.body,
215
- token: void 0
216
260
  }
217
261
  }
218
262
  };
@@ -221,18 +265,9 @@ class PluginAuthServer extends import_server.Plugin {
221
265
  {
222
266
  name: "auth:changePassword",
223
267
  getMetaData: async (ctx) => {
224
- var _a, _b, _c;
225
268
  return {
226
269
  request: {
227
- params: ctx.request.params,
228
- query: ctx.request.query,
229
- body: {},
230
- path: ctx.request.path,
231
- headers: {
232
- "x-authenticator": (_a = ctx.request) == null ? void 0 : _a.headers["x-authenticator"],
233
- "x-locale": (_b = ctx.request) == null ? void 0 : _b.headers["x-locale"],
234
- "x-timezone": (_c = ctx.request) == null ? void 0 : _c.headers["x-timezone"]
235
- }
270
+ body: {}
236
271
  },
237
272
  response: {
238
273
  body: {}
@@ -248,24 +283,47 @@ class PluginAuthServer extends import_server.Plugin {
248
283
  },
249
284
  "auth:signOut"
250
285
  ]);
286
+ this.app.acl.registerSnippet({
287
+ name: `pm.security.token-policy`,
288
+ actions: [`${import_constants.tokenPolicyCollectionName}:*`]
289
+ });
290
+ this.app.db.on(`${import_constants.tokenPolicyCollectionName}.afterSave`, async (model) => {
291
+ var _a;
292
+ (_a = this.app.authManager.tokenController) == null ? void 0 : _a.setConfig(model.config);
293
+ });
251
294
  }
252
295
  async install(options) {
253
- const repository = this.db.getRepository("authenticators");
254
- const exist = await repository.findOne({ filter: { name: import_preset.presetAuthenticator } });
255
- if (exist) {
296
+ const authRepository = this.db.getRepository("authenticators");
297
+ const exist = await authRepository.findOne({ filter: { name: import_preset.presetAuthenticator } });
298
+ if (!exist) {
299
+ await authRepository.create({
300
+ values: {
301
+ name: import_preset.presetAuthenticator,
302
+ authType: import_preset.presetAuthType,
303
+ description: "Sign in with username/email.",
304
+ enabled: true,
305
+ options: {
306
+ public: {
307
+ allowSignUp: true
308
+ }
309
+ }
310
+ }
311
+ });
312
+ }
313
+ const tokenPolicyRepo = this.app.db.getRepository(import_constants.tokenPolicyCollectionName);
314
+ const res = await tokenPolicyRepo.findOne({ filterByTk: import_constants.tokenPolicyRecordKey });
315
+ if (res) {
256
316
  return;
257
317
  }
258
- await repository.create({
318
+ const config = {
319
+ tokenExpirationTime: "1d",
320
+ sessionExpirationTime: "7d",
321
+ expiredTokenRenewLimit: "1d"
322
+ };
323
+ await tokenPolicyRepo.create({
259
324
  values: {
260
- name: import_preset.presetAuthenticator,
261
- authType: import_preset.presetAuthType,
262
- description: "Sign in with username/email.",
263
- enabled: true,
264
- options: {
265
- public: {
266
- allowSignUp: true
267
- }
268
- }
325
+ key: import_constants.tokenPolicyRecordKey,
326
+ config
269
327
  }
270
328
  });
271
329
  }
@@ -6,18 +6,24 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
- import { Storer as IStorer } from '@nocobase/auth';
9
+ import { AuthManager, Storer as IStorer } from '@nocobase/auth';
10
10
  import { Cache } from '@nocobase/cache';
11
11
  import { Database } from '@nocobase/database';
12
+ import { Application } from '@nocobase/server';
12
13
  import { AuthModel } from './model/authenticator';
13
14
  export declare class Storer implements IStorer {
14
15
  db: Database;
15
16
  cache: Cache;
17
+ app: Application;
18
+ authManager: AuthManager;
16
19
  key: string;
17
- constructor({ db, cache }: {
20
+ constructor({ app, db, cache, authManager, }: {
21
+ app?: Application;
18
22
  db: Database;
19
23
  cache: Cache;
24
+ authManager: AuthManager;
20
25
  });
26
+ renderJsonTemplate(authenticator: any): any;
21
27
  getCache(): Promise<AuthModel[]>;
22
28
  setCache(authenticators: AuthModel[]): Promise<void>;
23
29
  get(name: string): Promise<AuthModel>;