@nocobase/plugin-users 0.7.4-alpha.5 → 0.7.5-alpha.1

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.
@@ -1,6 +1,6 @@
1
1
  import { Context, Next } from '@nocobase/actions';
2
2
  export declare function check(ctx: Context, next: Next): Promise<void>;
3
- export declare function signin(ctx: Context, next: Next): Promise<void>;
3
+ export declare function signin(ctx: Context, next: Next): Promise<any>;
4
4
  export declare function signout(ctx: Context, next: Next): Promise<void>;
5
5
  export declare function signup(ctx: Context, next: Next): Promise<void>;
6
6
  export declare function lostpassword(ctx: Context, next: Next): Promise<void>;
@@ -13,6 +13,16 @@ exports.signout = signout;
13
13
  exports.signup = signup;
14
14
  exports.updateProfile = updateProfile;
15
15
 
16
+ function _resourcer() {
17
+ const data = require("@nocobase/resourcer");
18
+
19
+ _resourcer = function _resourcer() {
20
+ return data;
21
+ };
22
+
23
+ return data;
24
+ }
25
+
16
26
  function _crypto() {
17
27
  const data = _interopRequireDefault(require("crypto"));
18
28
 
@@ -27,11 +37,19 @@ var _ = require("../");
27
37
 
28
38
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
39
 
30
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
40
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
41
+
42
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
43
+
44
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
45
+
46
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
47
+
48
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
31
49
 
32
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
50
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
33
51
 
34
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
52
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
35
53
 
36
54
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
37
55
 
@@ -61,46 +79,44 @@ function signin(_x3, _x4) {
61
79
 
62
80
  function _signin() {
63
81
  _signin = _asyncToGenerator(function* (ctx, next) {
64
- const _ctx$action$params = ctx.action.params,
65
- _ctx$action$params$un = _ctx$action$params.uniqueField,
66
- uniqueField = _ctx$action$params$un === void 0 ? 'email' : _ctx$action$params$un,
67
- values = _ctx$action$params.values;
82
+ const _ctx$app$getPlugin = ctx.app.getPlugin('@nocobase/plugin-users'),
83
+ authenticators = _ctx$app$getPlugin.authenticators,
84
+ jwtService = _ctx$app$getPlugin.jwtService;
68
85
 
69
- if (!values[uniqueField]) {
70
- ctx.throw(401, ctx.t('Please fill in your email address', {
71
- ns: _.namespace
72
- }));
73
- }
86
+ const branches = {};
74
87
 
75
- const User = ctx.db.getCollection('users');
76
- const user = yield User.model.findOne({
77
- where: {
78
- [uniqueField]: values[uniqueField]
79
- }
80
- });
88
+ var _iterator = _createForOfIteratorHelper(authenticators.getEntities()),
89
+ _step;
81
90
 
82
- if (!user) {
83
- ctx.throw(401, ctx.t('The email is incorrect, please re-enter', {
84
- ns: _.namespace
85
- }));
86
- }
91
+ try {
92
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
93
+ const _step$value = _slicedToArray(_step.value, 2),
94
+ name = _step$value[0],
95
+ authenticator = _step$value[1];
87
96
 
88
- const pwd = User.getField('password');
89
- const isValid = yield pwd.verify(values.password, user.password);
90
-
91
- if (!isValid) {
92
- ctx.throw(401, ctx.t('The password is incorrect, please re-enter', {
93
- ns: _.namespace
94
- }));
97
+ branches[name] = authenticator;
98
+ }
99
+ } catch (err) {
100
+ _iterator.e(err);
101
+ } finally {
102
+ _iterator.f();
95
103
  }
96
104
 
97
- const pluginUser = ctx.app.getPlugin('@nocobase/plugin-users');
98
- ctx.body = _objectSpread(_objectSpread({}, user.toJSON()), {}, {
99
- token: pluginUser.jwtService.sign({
100
- userId: user.get('id')
101
- })
105
+ return (0, _resourcer().branch)(branches, context => {
106
+ var _context$action$param;
107
+
108
+ return (_context$action$param = context.action.params.authenticator) !== null && _context$action$param !== void 0 ? _context$action$param : 'password';
109
+ })(ctx, () => {
110
+ const user = ctx.state.currentUser.toJSON();
111
+ const token = jwtService.sign({
112
+ userId: user.id
113
+ });
114
+ ctx.body = {
115
+ user,
116
+ token
117
+ };
118
+ return next();
102
119
  });
103
- yield next();
104
120
  });
105
121
  return _signin.apply(this, arguments);
106
122
  }
@@ -143,9 +159,12 @@ function _lostpassword() {
143
159
  const email = ctx.action.params.values.email;
144
160
 
145
161
  if (!email) {
146
- ctx.throw(401, ctx.t('Please fill in your email address', {
147
- ns: _.namespace
148
- }));
162
+ ctx.throw(400, {
163
+ code: 'InvalidUserData',
164
+ message: ctx.t('Please fill in your email address', {
165
+ ns: _.namespace
166
+ })
167
+ });
149
168
  }
150
169
 
151
170
  const User = ctx.db.getCollection('users');
@@ -156,9 +175,12 @@ function _lostpassword() {
156
175
  });
157
176
 
158
177
  if (!user) {
159
- ctx.throw(401, ctx.t('The email is incorrect, please re-enter', {
160
- ns: _.namespace
161
- }));
178
+ ctx.throw(404, {
179
+ code: 'InvalidUserData',
180
+ message: ctx.t('The email is incorrect, please re-enter', {
181
+ ns: _.namespace
182
+ })
183
+ });
162
184
  }
163
185
 
164
186
  user.resetToken = _crypto().default.randomBytes(20).toString('hex');
@@ -188,7 +210,7 @@ function _resetpassword() {
188
210
  });
189
211
 
190
212
  if (!user) {
191
- ctx.throw(401, 'Unauthorized');
213
+ ctx.throw(404);
192
214
  }
193
215
 
194
216
  user.token = null;
@@ -216,7 +238,7 @@ function _getUserByResetToken() {
216
238
  });
217
239
 
218
240
  if (!user) {
219
- ctx.throw(401, 'Unauthorized');
241
+ ctx.throw(401);
220
242
  }
221
243
 
222
244
  ctx.body = user;
@@ -232,13 +254,18 @@ function updateProfile(_x15, _x16) {
232
254
  function _updateProfile() {
233
255
  _updateProfile = _asyncToGenerator(function* (ctx, next) {
234
256
  const values = ctx.action.params.values;
257
+ const currentUser = ctx.state.currentUser;
235
258
 
236
- if (!ctx.state.currentUser) {
237
- ctx.throw(401, 'Unauthorized');
259
+ if (!currentUser) {
260
+ ctx.throw(401);
238
261
  }
239
262
 
240
- yield ctx.state.currentUser.update(values);
241
- ctx.body = ctx.state.currentUser;
263
+ const UserRepo = ctx.db.getRepository('users');
264
+ const result = yield UserRepo.update({
265
+ filterByTk: currentUser.id,
266
+ values
267
+ });
268
+ ctx.body = result;
242
269
  yield next();
243
270
  });
244
271
  return _updateProfile.apply(this, arguments);
@@ -255,7 +282,7 @@ function _changePassword() {
255
282
  newPassword = _ctx$action$params$va2.newPassword;
256
283
 
257
284
  if (!ctx.state.currentUser) {
258
- ctx.throw(401, 'Unauthorized');
285
+ ctx.throw(401);
259
286
  }
260
287
 
261
288
  const User = ctx.db.getCollection('users');
@@ -0,0 +1,7 @@
1
+ import { HandlerType } from '@nocobase/resourcer';
2
+ import Plugin from '..';
3
+ interface Authenticators {
4
+ [key: string]: HandlerType;
5
+ }
6
+ export default function (plugin: Plugin, more?: Authenticators): void;
7
+ export {};
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = _default;
7
+
8
+ function _path() {
9
+ const data = _interopRequireDefault(require("path"));
10
+
11
+ _path = function _path() {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
17
+
18
+ function _utils() {
19
+ const data = require("@nocobase/utils");
20
+
21
+ _utils = function _utils() {
22
+ return data;
23
+ };
24
+
25
+ return data;
26
+ }
27
+
28
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29
+
30
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
31
+
32
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
33
+
34
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
35
+
36
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
37
+
38
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
39
+
40
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
41
+
42
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
43
+
44
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
45
+
46
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
47
+
48
+ ;
49
+
50
+ function _default(plugin, more = {}) {
51
+ const authenticators = plugin.authenticators;
52
+ const natives = ['password'].reduce((result, key) => Object.assign(result, {
53
+ [key]: (0, _utils().requireModule)(_path().default.isAbsolute(key) ? key : _path().default.join(__dirname, key))
54
+ }), {});
55
+
56
+ for (var _i = 0, _Object$entries = Object.entries(_objectSpread(_objectSpread({}, more), natives)); _i < _Object$entries.length; _i++) {
57
+ const _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
58
+ name = _Object$entries$_i[0],
59
+ authenticator = _Object$entries$_i[1];
60
+
61
+ authenticators.register(name, authenticator);
62
+ }
63
+ }
@@ -0,0 +1,2 @@
1
+ import { Context, Next } from '@nocobase/actions';
2
+ export default function (ctx: Context, next: Next): Promise<any>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = _default;
7
+
8
+ var _ = require("..");
9
+
10
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
11
+
12
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
13
+
14
+ function _default(_x, _x2) {
15
+ return _ref.apply(this, arguments);
16
+ }
17
+
18
+ function _ref() {
19
+ _ref = _asyncToGenerator(function* (ctx, next) {
20
+ const _ctx$action$params = ctx.action.params,
21
+ _ctx$action$params$un = _ctx$action$params.uniqueField,
22
+ uniqueField = _ctx$action$params$un === void 0 ? 'email' : _ctx$action$params$un,
23
+ values = _ctx$action$params.values;
24
+
25
+ if (!values[uniqueField]) {
26
+ return ctx.throw(400, {
27
+ code: 'InvalidUserData',
28
+ message: ctx.t('Please fill in your email address', {
29
+ ns: _.namespace
30
+ })
31
+ });
32
+ }
33
+
34
+ const User = ctx.db.getCollection('users');
35
+ const user = yield User.model.findOne({
36
+ where: {
37
+ [uniqueField]: values[uniqueField]
38
+ }
39
+ });
40
+
41
+ if (!user) {
42
+ return ctx.throw(404, ctx.t('The email is incorrect, please re-enter', {
43
+ ns: _.namespace
44
+ }));
45
+ }
46
+
47
+ const field = User.getField('password');
48
+ const valid = yield field.verify(values.password, user.password);
49
+
50
+ if (!valid) {
51
+ return ctx.throw(404, ctx.t('The password is incorrect, please re-enter', {
52
+ ns: _.namespace
53
+ }));
54
+ }
55
+
56
+ ctx.state.currentUser = user;
57
+ return next();
58
+ });
59
+ return _ref.apply(this, arguments);
60
+ }
@@ -46,6 +46,18 @@ var _default = {
46
46
  'x-validator': 'email',
47
47
  require: true
48
48
  }
49
+ }, {
50
+ interface: 'phone',
51
+ type: 'string',
52
+ name: 'phone',
53
+ unique: true,
54
+ uiSchema: {
55
+ type: 'string',
56
+ title: '{{t("Phone")}}',
57
+ 'x-component': 'Input',
58
+ 'x-validator': 'phone',
59
+ require: true
60
+ }
49
61
  }, {
50
62
  interface: 'password',
51
63
  type: 'password',
@@ -0,0 +1,5 @@
1
+ declare const _default: {
2
+ 'Please fill in your email address': string;
3
+ 'The password is incorrect, please re-enter': string;
4
+ };
5
+ export default _default;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _default = {
8
+ 'Please fill in your email address': 'メールアドレスを入力してください',
9
+ 'The password is incorrect, please re-enter': 'パスワードが正しくありません。再度入力してください。'
10
+ };
11
+ exports.default = _default;
@@ -2,5 +2,8 @@ declare const _default: {
2
2
  'The email is incorrect, please re-enter': string;
3
3
  'Please fill in your email address': string;
4
4
  'The password is incorrect, please re-enter': string;
5
+ 'Not a valid cellphone number, please re-enter': string;
6
+ 'The phone number has been registered, please login directly': string;
7
+ 'The phone number is not registered, please register first': string;
5
8
  };
6
9
  export default _default;
@@ -5,8 +5,11 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
  var _default = {
8
- 'The email is incorrect, please re-enter': '邮箱错误,请重新输入',
9
- 'Please fill in your email address': '请填写密码',
10
- 'The password is incorrect, please re-enter': '密码错误,请重新输入'
8
+ 'The email is incorrect, please re-enter': '邮箱有误,请重新输入',
9
+ 'Please fill in your email address': '请填写邮箱',
10
+ 'The password is incorrect, please re-enter': '密码有误,请重新输入',
11
+ 'Not a valid cellphone number, please re-enter': '不是有效的手机号,请重新输入',
12
+ 'The phone number has been registered, please login directly': '手机号已注册,请直接登录',
13
+ 'The phone number is not registered, please register first': '手机号未注册,请先注册'
11
14
  };
12
15
  exports.default = _default;
@@ -1,5 +1,2 @@
1
- import { MiddlewareManager } from '@nocobase/resourcer';
2
- import UsersPlugin from '../server';
3
- export declare function parseToken(options?: {
4
- plugin: UsersPlugin;
5
- }): MiddlewareManager;
1
+ import { Context, Next } from '@nocobase/actions';
2
+ export declare function parseToken(ctx: Context, next: Next): Promise<any>;
@@ -5,16 +5,6 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.parseToken = parseToken;
7
7
 
8
- function _resourcer() {
9
- const data = require("@nocobase/resourcer");
10
-
11
- _resourcer = function _resourcer() {
12
- return data;
13
- };
14
-
15
- return data;
16
- }
17
-
18
8
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
19
9
 
20
10
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
@@ -33,41 +23,41 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try
33
23
 
34
24
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
35
25
 
36
- function parseToken(options) {
37
- const middleware = new (_resourcer().MiddlewareManager)();
38
- middleware.use( /*#__PURE__*/function () {
39
- var _ref = _asyncToGenerator(function* (ctx, next) {
40
- const user = yield findUserByToken(ctx, options.plugin);
26
+ function parseToken(_x, _x2) {
27
+ return _parseToken.apply(this, arguments);
28
+ }
41
29
 
42
- if (user) {
43
- ctx.state.currentUser = user;
44
- }
30
+ function _parseToken() {
31
+ _parseToken = _asyncToGenerator(function* (ctx, next) {
32
+ const user = yield findUserByToken(ctx);
45
33
 
46
- return next();
47
- });
34
+ if (user) {
35
+ ctx.state.currentUser = user;
36
+ }
48
37
 
49
- return function (_x, _x2) {
50
- return _ref.apply(this, arguments);
51
- };
52
- }());
53
- return middleware;
38
+ return next();
39
+ });
40
+ return _parseToken.apply(this, arguments);
54
41
  }
55
42
 
56
- function findUserByToken(_x3, _x4) {
43
+ function findUserByToken(_x3) {
57
44
  return _findUserByToken.apply(this, arguments);
58
45
  }
59
46
 
60
47
  function _findUserByToken() {
61
- _findUserByToken = _asyncToGenerator(function* (ctx, plugin) {
48
+ _findUserByToken = _asyncToGenerator(function* (ctx) {
62
49
  const token = ctx.getBearerToken();
63
50
 
64
51
  if (!token) {
65
52
  return null;
66
53
  }
67
54
 
55
+ const _ctx$app$getPlugin = ctx.app.getPlugin('@nocobase/plugin-users'),
56
+ jwtService = _ctx$app$getPlugin.jwtService;
57
+
68
58
  try {
69
- const _yield$plugin$jwtServ = yield plugin.jwtService.decode(token),
70
- userId = _yield$plugin$jwtServ.userId;
59
+ const _yield$jwtService$dec = yield jwtService.decode(token),
60
+ userId = _yield$jwtService$dec.userId;
71
61
 
72
62
  const collection = ctx.db.getCollection('users');
73
63
  ctx.state.currentUserAppends = ctx.state.currentUserAppends || [];
@@ -90,13 +80,15 @@ function _findUserByToken() {
90
80
  _iterator.f();
91
81
  }
92
82
 
93
- return yield ctx.db.getRepository('users').findOne({
83
+ const user = yield ctx.db.getRepository('users').findOne({
94
84
  appends: ctx.state.currentUserAppends,
95
85
  filter: {
96
86
  id: userId
97
87
  }
98
88
  });
89
+ return user;
99
90
  } catch (error) {
91
+ console.log(error);
100
92
  return null;
101
93
  }
102
94
  });
@@ -0,0 +1,5 @@
1
+ import { Migration } from '@nocobase/server';
2
+ export default class AddUsersPhoneMigration extends Migration {
3
+ up(): Promise<void>;
4
+ down(): Promise<void>;
5
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ function _server() {
9
+ const data = require("@nocobase/server");
10
+
11
+ _server = function _server() {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
17
+
18
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
19
+
20
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
21
+
22
+ class AddUsersPhoneMigration extends _server().Migration {
23
+ up() {
24
+ var _this = this;
25
+
26
+ return _asyncToGenerator(function* () {
27
+ const match = yield _this.app.version.satisfies('<=0.7.4-alpha.7');
28
+
29
+ if (!match) {
30
+ return;
31
+ }
32
+
33
+ const Field = _this.context.db.getRepository('fields');
34
+
35
+ const existed = yield Field.count({
36
+ filter: {
37
+ name: 'phone',
38
+ collectionName: 'users'
39
+ }
40
+ });
41
+
42
+ if (!existed) {
43
+ yield Field.create({
44
+ values: {
45
+ name: 'phone',
46
+ collectionName: 'users',
47
+ type: 'string',
48
+ unique: true,
49
+ interface: 'phone',
50
+ uiSchema: {
51
+ type: 'string',
52
+ title: '{{t("Phone")}}',
53
+ 'x-component': 'Input',
54
+ 'x-validator': 'phone',
55
+ require: true
56
+ }
57
+ },
58
+ // NOTE: to trigger hook
59
+ context: {}
60
+ });
61
+ }
62
+ })();
63
+ }
64
+
65
+ down() {
66
+ return _asyncToGenerator(function* () {})();
67
+ }
68
+
69
+ }
70
+
71
+ exports.default = AddUsersPhoneMigration;
package/lib/server.d.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import { Plugin } from '@nocobase/server';
2
+ import { Registry } from '@nocobase/utils';
3
+ import { HandlerType, Middleware } from '@nocobase/resourcer';
2
4
  import { JwtOptions, JwtService } from './jwt-service';
3
5
  export interface UserPluginConfig {
4
6
  jwt: JwtOptions;
5
7
  }
6
8
  export default class UsersPlugin extends Plugin<UserPluginConfig> {
7
9
  jwtService: JwtService;
8
- tokenMiddleware: any;
10
+ tokenMiddleware: Middleware;
11
+ authenticators: Registry<HandlerType>;
9
12
  constructor(app: any, options: any);
10
13
  beforeLoad(): Promise<void>;
11
14
  load(): Promise<void>;
package/lib/server.js CHANGED
@@ -5,6 +5,26 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.default = void 0;
7
7
 
8
+ function _path() {
9
+ const data = require("path");
10
+
11
+ _path = function _path() {
12
+ return data;
13
+ };
14
+
15
+ return data;
16
+ }
17
+
18
+ function _jsonTemplates() {
19
+ const data = _interopRequireDefault(require("json-templates"));
20
+
21
+ _jsonTemplates = function _jsonTemplates() {
22
+ return data;
23
+ };
24
+
25
+ return data;
26
+ }
27
+
8
28
  function _database() {
9
29
  const data = require("@nocobase/database");
10
30
 
@@ -25,20 +45,20 @@ function _server() {
25
45
  return data;
26
46
  }
27
47
 
28
- function _jsonTemplates() {
29
- const data = _interopRequireDefault(require("json-templates"));
48
+ function _utils() {
49
+ const data = require("@nocobase/utils");
30
50
 
31
- _jsonTemplates = function _jsonTemplates() {
51
+ _utils = function _utils() {
32
52
  return data;
33
53
  };
34
54
 
35
55
  return data;
36
56
  }
37
57
 
38
- function _path() {
39
- const data = require("path");
58
+ function _resourcer() {
59
+ const data = require("@nocobase/resourcer");
40
60
 
41
- _path = function _path() {
61
+ _resourcer = function _resourcer() {
42
62
  return data;
43
63
  };
44
64
 
@@ -53,7 +73,9 @@ var _jwtService = require("./jwt-service");
53
73
 
54
74
  var _locale = require("./locale");
55
75
 
56
- var middlewares = _interopRequireWildcard(require("./middlewares"));
76
+ var _middlewares = require("./middlewares");
77
+
78
+ var _authenticators = _interopRequireDefault(require("./authenticators"));
57
79
 
58
80
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
59
81
 
@@ -82,10 +104,9 @@ class UsersPlugin extends _server().Plugin {
82
104
  super(app, options);
83
105
  this.jwtService = void 0;
84
106
  this.tokenMiddleware = void 0;
107
+ this.authenticators = new (_utils().Registry)();
85
108
  this.jwtService = new _jwtService.JwtService((options === null || options === void 0 ? void 0 : options.jwt) || {});
86
- this.tokenMiddleware = middlewares.parseToken({
87
- plugin: this
88
- });
109
+ this.tokenMiddleware = new (_resourcer().Middleware)(_middlewares.parseToken);
89
110
  }
90
111
 
91
112
  beforeLoad() {
@@ -101,7 +122,7 @@ class UsersPlugin extends _server().Plugin {
101
122
  if (cmd) {
102
123
  cmd.requiredOption('-e, --root-email <rootEmail>', '', process.env.INIT_ROOT_EMAIL);
103
124
  cmd.requiredOption('-p, --root-password <rootPassword>', '', process.env.INIT_ROOT_PASSWORD);
104
- cmd.option('-n, --root-nickname [rootNickname]');
125
+ cmd.option('-n, --root-nickname <rootNickname>');
105
126
  }
106
127
 
107
128
  _this.db.registerOperators({
@@ -173,7 +194,7 @@ class UsersPlugin extends _server().Plugin {
173
194
  _this.app.resourcer.registerActionHandler(`users:${key}`, action);
174
195
  }
175
196
 
176
- _this.app.resourcer.use(_this.tokenMiddleware.compose());
197
+ _this.app.resourcer.use(_this.tokenMiddleware.getHandler());
177
198
 
178
199
  const publicActions = ['check', 'signin', 'signup', 'lostpassword', 'resetpassword', 'getUserByResetToken'];
179
200
  const loggedInActions = ['signout', 'updateProfile', 'changePassword'];
@@ -189,6 +210,119 @@ class UsersPlugin extends _server().Plugin {
189
210
  yield _this2.db.import({
190
211
  directory: (0, _path().resolve)(__dirname, 'collections')
191
212
  });
213
+
214
+ _this2.db.addMigrations({
215
+ namespace: 'users',
216
+ directory: (0, _path().resolve)(__dirname, 'migrations'),
217
+ context: {
218
+ plugin: _this2
219
+ }
220
+ });
221
+
222
+ (0, _authenticators.default)(_this2); // TODO(module): should move to preset
223
+
224
+ const verificationPlugin = _this2.app.getPlugin('@nocobase/plugin-verification');
225
+
226
+ if (verificationPlugin && process.env.DEFAULT_SMS_VERIFY_CODE_PROVIDER) {
227
+ verificationPlugin.interceptors.register('users:signin', {
228
+ manual: true,
229
+ provider: process.env.DEFAULT_SMS_VERIFY_CODE_PROVIDER,
230
+
231
+ getReceiver(ctx) {
232
+ return ctx.action.params.values.phone;
233
+ },
234
+
235
+ expiresIn: 120,
236
+ validate: function () {
237
+ var _validate = _asyncToGenerator(function* (ctx, phone) {
238
+ if (!phone) {
239
+ throw new Error(ctx.t('Not a valid cellphone number, please re-enter'));
240
+ }
241
+
242
+ const User = _this2.db.getCollection('users');
243
+
244
+ const exists = yield User.model.count({
245
+ where: {
246
+ phone
247
+ }
248
+ });
249
+
250
+ if (!exists) {
251
+ throw new Error(ctx.t('The phone number is not registered, please register first', {
252
+ ns: _2.namespace
253
+ }));
254
+ }
255
+
256
+ return true;
257
+ });
258
+
259
+ function validate(_x, _x2) {
260
+ return _validate.apply(this, arguments);
261
+ }
262
+
263
+ return validate;
264
+ }()
265
+ });
266
+ verificationPlugin.interceptors.register('users:signup', {
267
+ provider: process.env.DEFAULT_SMS_VERIFY_CODE_PROVIDER,
268
+
269
+ getReceiver(ctx) {
270
+ return ctx.action.params.values.phone;
271
+ },
272
+
273
+ expiresIn: 120,
274
+ validate: function () {
275
+ var _validate2 = _asyncToGenerator(function* (ctx, phone) {
276
+ if (!phone) {
277
+ throw new Error(ctx.t('Not a valid cellphone number, please re-enter', {
278
+ ns: _2.namespace
279
+ }));
280
+ }
281
+
282
+ const User = _this2.db.getCollection('users');
283
+
284
+ const exists = yield User.model.count({
285
+ where: {
286
+ phone
287
+ }
288
+ });
289
+
290
+ if (exists) {
291
+ throw new Error(ctx.t('The phone number has been registered, please login directly', {
292
+ ns: _2.namespace
293
+ }));
294
+ }
295
+
296
+ return true;
297
+ });
298
+
299
+ function validate(_x3, _x4) {
300
+ return _validate2.apply(this, arguments);
301
+ }
302
+
303
+ return validate;
304
+ }()
305
+ });
306
+
307
+ _this2.authenticators.register('sms', (ctx, next) => verificationPlugin.intercept(ctx, /*#__PURE__*/_asyncToGenerator(function* () {
308
+ const values = ctx.action.params.values;
309
+ const User = ctx.db.getCollection('users');
310
+ const user = yield User.model.findOne({
311
+ where: {
312
+ phone: values.phone
313
+ }
314
+ });
315
+
316
+ if (!user) {
317
+ return ctx.throw(404, ctx.t('The phone number is incorrect, please re-enter', {
318
+ ns: _2.namespace
319
+ }));
320
+ }
321
+
322
+ ctx.state.currentUser = user;
323
+ return next();
324
+ })));
325
+ }
192
326
  })();
193
327
  }
194
328
 
@@ -200,13 +334,13 @@ class UsersPlugin extends _server().Plugin {
200
334
  INIT_ROOT_PASSWORD = _process$env.INIT_ROOT_PASSWORD,
201
335
  INIT_ROOT_EMAIL = _process$env.INIT_ROOT_EMAIL;
202
336
 
203
- const _ref = options.users || (options === null || options === void 0 ? void 0 : (_options$cliArgs = options.cliArgs) === null || _options$cliArgs === void 0 ? void 0 : _options$cliArgs[0]) || {},
204
- _ref$rootEmail = _ref.rootEmail,
205
- rootEmail = _ref$rootEmail === void 0 ? INIT_ROOT_EMAIL : _ref$rootEmail,
206
- _ref$rootPassword = _ref.rootPassword,
207
- rootPassword = _ref$rootPassword === void 0 ? INIT_ROOT_PASSWORD : _ref$rootPassword,
208
- _ref$rootNickname = _ref.rootNickname,
209
- rootNickname = _ref$rootNickname === void 0 ? INIT_ROOT_NICKNAME || 'Super Admin' : _ref$rootNickname;
337
+ const _ref2 = options.users || (options === null || options === void 0 ? void 0 : (_options$cliArgs = options.cliArgs) === null || _options$cliArgs === void 0 ? void 0 : _options$cliArgs[0]) || {},
338
+ _ref2$rootEmail = _ref2.rootEmail,
339
+ rootEmail = _ref2$rootEmail === void 0 ? INIT_ROOT_EMAIL : _ref2$rootEmail,
340
+ _ref2$rootPassword = _ref2.rootPassword,
341
+ rootPassword = _ref2$rootPassword === void 0 ? INIT_ROOT_PASSWORD : _ref2$rootPassword,
342
+ _ref2$rootNickname = _ref2.rootNickname,
343
+ rootNickname = _ref2$rootNickname === void 0 ? INIT_ROOT_NICKNAME || 'Super Admin' : _ref2$rootNickname;
210
344
 
211
345
  return {
212
346
  rootEmail,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocobase/plugin-users",
3
- "version": "0.7.4-alpha.5",
3
+ "version": "0.7.5-alpha.1",
4
4
  "main": "lib/index.js",
5
5
  "license": "Apache-2.0",
6
6
  "licenses": [
@@ -10,12 +10,17 @@
10
10
  }
11
11
  ],
12
12
  "dependencies": {
13
+ "@nocobase/actions": "0.7.5-alpha.1",
14
+ "@nocobase/database": "0.7.5-alpha.1",
15
+ "@nocobase/resourcer": "0.7.5-alpha.1",
16
+ "@nocobase/server": "0.7.5-alpha.1",
17
+ "@nocobase/utils": "0.7.5-alpha.1",
18
+ "json-templates": "^4.2.0",
13
19
  "jsonwebtoken": "^8.5.1"
14
20
  },
15
21
  "devDependencies": {
16
- "@nocobase/test": "0.7.4-alpha.5",
17
- "@types/jsonwebtoken": "^8.5.8",
18
- "json-templates": "^4.2.0"
22
+ "@nocobase/test": "0.7.5-alpha.1",
23
+ "@types/jsonwebtoken": "^8.5.8"
19
24
  },
20
- "gitHead": "0fbd32afad99b610509cf7093ed027aa727880c1"
25
+ "gitHead": "f6eb27b68185bb0c0b4c2cfca1df84205a9b9173"
21
26
  }