@opencampus/ocid-connect-js 1.2.1 → 1.2.3

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.
package/README.md CHANGED
@@ -110,7 +110,7 @@ Use useOCAuth hook to read credentials info
110
110
  import { useOCAuth } from '@opencampus/ocid-connect-js';
111
111
 
112
112
  const UserTokenPage = (props) => {
113
- const { authState, ocAuth } = useOCAuth();
113
+ const { authState, ocAuth, OCId, ethAddress } = useOCAuth();
114
114
 
115
115
  if (authState.error !== undefined) {
116
116
  return <div>Error: {authState.error.message}</div>;
@@ -119,8 +119,10 @@ const UserTokenPage = (props) => {
119
119
  <div>
120
120
  <h4>User Info</h4>
121
121
  <pre>
122
- { JSON.stringify(ocAuth.getAuthInfo(), null, 2) }
122
+ { JSON.stringify(ocAuth.getAuthState(), null, 2) }
123
123
  </pre>
124
+ <pre>{OCId}</pre>
125
+ <pre>{ethAddress}</pre>
124
126
  </div>
125
127
  );
126
128
  }
@@ -298,7 +300,7 @@ export default function Home() {
298
300
  <div>
299
301
  <h1>Welcome to My App</h1>
300
302
  {authState.isAuthenticated ? (
301
- <p>You are logged in! {JSON.stringify(ocAuth.getAuthInfo())}</p>
303
+ <p>You are logged in! {JSON.stringify(ocAuth.getAuthState())}</p>
302
304
 
303
305
  ) : (
304
306
  <LoginButton />
@@ -328,8 +330,8 @@ Main Methods of Auth SDK
328
330
  | --- | --- |
329
331
  | signInWithRedirect | Initialize login process. Accept "state" as an input |
330
332
  | handleLoginRedirect | Return the auth state of the login process |
331
- | getAuthInfo | Return auth object { edu_username, eth_address } |
332
- | getAuthState | Return auth state data { accessToken, idToken, isAuthenticated } |
333
+ | getAuthState | Return auth state data { accessToken, idToken, OCId, ethAddress, isAuthenticated } |
334
+ | getStateParameter() | Return the state that was initialized in signin process |
333
335
 
334
336
  Sample usage
335
337
 
@@ -369,5 +371,12 @@ try {
369
371
  }
370
372
  ```
371
373
 
374
+ Access OCId info of Auth SDK
375
+
376
+ | property | Description |
377
+ | --- | --- |
378
+ | OCId | return OC ID |
379
+ | ethAddress | Return eth Wallet Address that connect to the ID |
380
+
372
381
  ### License
373
382
  ocid-connect-js is released under the MIT license.
@@ -360,51 +360,36 @@ var LoginCallBack = function LoginCallBack(_ref) {
360
360
  var _useOCAuth = Object(_OCContext__WEBPACK_IMPORTED_MODULE_1__["useOCAuth"])(),
361
361
  ocAuth = _useOCAuth.ocAuth,
362
362
  authState = _useOCAuth.authState,
363
- updateAuthState = _useOCAuth.updateAuthState;
363
+ setAuthError = _useOCAuth.setAuthError;
364
364
  Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(function () {
365
365
  var handleLogin = /*#__PURE__*/function () {
366
366
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
367
- var _authState;
368
367
  return _regeneratorRuntime().wrap(function _callee$(_context) {
369
368
  while (1) switch (_context.prev = _context.next) {
370
369
  case 0:
371
370
  if (!ocAuth) {
372
- _context.next = 12;
371
+ _context.next = 11;
373
372
  break;
374
373
  }
375
374
  _context.prev = 1;
376
375
  _context.next = 4;
377
376
  return ocAuth.handleLoginRedirect();
378
377
  case 4:
379
- _authState = _context.sent;
380
- if (_authState.idToken) {
381
- updateAuthState(_authState);
382
- handledRedirect = true;
383
- successCallback();
384
- } else {
385
- updateAuthState({
386
- error: 'missing idToken from redirect callback'
387
- });
388
- if (errorCallback) {
389
- errorCallback();
390
- }
391
- }
392
- _context.next = 12;
378
+ successCallback();
379
+ _context.next = 11;
393
380
  break;
394
- case 8:
395
- _context.prev = 8;
381
+ case 7:
382
+ _context.prev = 7;
396
383
  _context.t0 = _context["catch"](1);
397
- updateAuthState({
398
- error: _context.t0
399
- });
384
+ setAuthError(_context.t0);
400
385
  if (errorCallback) {
401
386
  errorCallback();
402
387
  }
403
- case 12:
388
+ case 11:
404
389
  case "end":
405
390
  return _context.stop();
406
391
  }
407
- }, _callee, null, [[1, 8]]);
392
+ }, _callee, null, [[1, 7]]);
408
393
  }));
409
394
  return function handleLogin() {
410
395
  return _ref2.apply(this, arguments);
@@ -458,34 +443,53 @@ var OCConnect = function OCConnect(_ref) {
458
443
  _useState2 = _slicedToArray(_useState, 2),
459
444
  ocAuth = _useState2[0],
460
445
  setOcAuth = _useState2[1];
461
- var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])({
446
+ var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(),
447
+ _useState4 = _slicedToArray(_useState3, 2),
448
+ OCId = _useState4[0],
449
+ setOCId = _useState4[1];
450
+ var _useState5 = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(),
451
+ _useState6 = _slicedToArray(_useState5, 2),
452
+ ethAddress = _useState6[0],
453
+ setEthAddress = _useState6[1];
454
+ var _useState7 = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])({
462
455
  isAuthenticated: false
463
456
  }),
464
- _useState4 = _slicedToArray(_useState3, 2),
465
- authState = _useState4[0],
466
- setAuthState = _useState4[1];
457
+ _useState8 = _slicedToArray(_useState7, 2),
458
+ authState = _useState8[0],
459
+ setAuthState = _useState8[1];
460
+ var _useState9 = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(null),
461
+ _useState10 = _slicedToArray(_useState9, 2),
462
+ authError = _useState10[0],
463
+ setAuthError = _useState10[1];
464
+ var updateAuthState = function updateAuthState(authState) {
465
+ setAuthState(authState);
466
+ setOCId(authState.OCId);
467
+ setEthAddress(authState.ethAddress);
468
+ };
469
+
470
+ // init sdk
467
471
  Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(function () {
468
472
  var authSdk = sandboxMode ? new _sdk_auth__WEBPACK_IMPORTED_MODULE_2__["OCAuthSandbox"](opts) : new _sdk_auth__WEBPACK_IMPORTED_MODULE_2__["OCAuthLive"](opts);
469
- setOcAuth(authSdk);
470
473
  updateAuthState(authSdk.getAuthState());
474
+ setOcAuth(authSdk);
471
475
  }, []);
472
- var updateAuthState = function updateAuthState(authState) {
473
- var accessToken = authState.accessToken,
474
- idToken = authState.idToken,
475
- isAuthenticated = authState.isAuthenticated,
476
- error = authState.error;
477
- setAuthState({
478
- accessToken: accessToken,
479
- idToken: idToken,
480
- isAuthenticated: isAuthenticated,
481
- error: error
482
- });
483
- };
476
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(function () {
477
+ if (ocAuth.authInfoManager) {
478
+ // reactively recieve update on the authstate change
479
+ ocAuth.authInfoManager.subscribe(updateAuthState);
480
+ return function () {
481
+ ocAuth.authInfoManager.unsubscribe(updateAuthState);
482
+ };
483
+ }
484
+ }, [ocAuth]);
484
485
  return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_OCContext__WEBPACK_IMPORTED_MODULE_1__["OCContext"].Provider, {
485
486
  value: {
487
+ OCId: OCId,
488
+ ethAddress: ethAddress,
486
489
  ocAuth: ocAuth,
487
490
  authState: authState,
488
- updateAuthState: updateAuthState
491
+ authError: authError,
492
+ setAuthError: setAuthError
489
493
  }
490
494
  }, children);
491
495
  };
@@ -568,21 +572,24 @@ var OCAuthCore = /*#__PURE__*/function () {
568
572
  }, {
569
573
  key: "logout",
570
574
  value: function () {
571
- var _logout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
572
- var requestUrl;
575
+ var _logout = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(logoutReturnTo) {
576
+ var url;
573
577
  return _regeneratorRuntime().wrap(function _callee$(_context) {
574
578
  while (1) switch (_context.prev = _context.next) {
575
579
  case 0:
576
580
  this.clearStorage();
577
- requestUrl = this.logoutEndPoint;
578
- window.location.assign(requestUrl);
579
- case 3:
581
+ url = new URL(this.logoutEndPoint);
582
+ if (logoutReturnTo) {
583
+ url.searchParams.append('returnTo', logoutReturnTo);
584
+ }
585
+ window.location.assign(url.toString());
586
+ case 4:
580
587
  case "end":
581
588
  return _context.stop();
582
589
  }
583
590
  }, _callee, this);
584
591
  }));
585
- function logout() {
592
+ function logout(_x) {
586
593
  return _logout.apply(this, arguments);
587
594
  }
588
595
  return logout;
@@ -614,7 +621,7 @@ var OCAuthCore = /*#__PURE__*/function () {
614
621
  }
615
622
  }, _callee2, this);
616
623
  }));
617
- function signInWithRedirect(_x) {
624
+ function signInWithRedirect(_x2) {
618
625
  return _signInWithRedirect.apply(this, arguments);
619
626
  }
620
627
  return signInWithRedirect;
@@ -639,7 +646,7 @@ var OCAuthCore = /*#__PURE__*/function () {
639
646
  break;
640
647
  }
641
648
  _context3.next = 7;
642
- return this.tokenManager.exchangeTokenFromCode(urlParams.code, codeVerifier);
649
+ return this.tokenManager.exchangeTokenFromCode(urlParams.code, codeVerifier, urlParams.state);
643
650
  case 7:
644
651
  // clear transaction meta, coz it's completed
645
652
  this.transactionManager.clear();
@@ -675,26 +682,18 @@ var OCAuthCore = /*#__PURE__*/function () {
675
682
  var _this$getParsedIdToke = this.getParsedIdToken(),
676
683
  edu_username = _this$getParsedIdToke.edu_username,
677
684
  eth_address = _this$getParsedIdToke.eth_address;
678
- this.authInfoManager.setIdInfo({
679
- edu_username: edu_username,
680
- eth_address: eth_address
681
- });
685
+ this.authInfoManager.setAuthState(this.getAccessToken(), this.getIdToken(), edu_username, eth_address, this.isAuthenticated());
682
686
  }
683
687
  }
684
688
  }, {
685
689
  key: "getAuthState",
686
690
  value: function getAuthState() {
687
- var authState = {
688
- accessToken: this.getAccessToken(),
689
- idToken: this.getIdToken(),
690
- isAuthenticated: this.isAuthenticated()
691
- };
692
- return authState;
691
+ return this.authInfoManager.getAuthState();
693
692
  }
694
693
  }, {
695
- key: "getAuthInfo",
696
- value: function getAuthInfo() {
697
- return this.authInfoManager.getAuthInfo();
694
+ key: "getStateParameter",
695
+ value: function getStateParameter() {
696
+ return this.tokenManager.getStateParameter();
698
697
  }
699
698
  }, {
700
699
  key: "getIdToken",
@@ -726,6 +725,20 @@ var OCAuthCore = /*#__PURE__*/function () {
726
725
  }
727
726
  return {};
728
727
  }
728
+ }, {
729
+ key: "OCId",
730
+ get: function get() {
731
+ var _info$OCId;
732
+ var info = this.authInfoManager.getAuthState();
733
+ return (_info$OCId = info.OCId) !== null && _info$OCId !== void 0 ? _info$OCId : null;
734
+ }
735
+ }, {
736
+ key: "ethAddress",
737
+ get: function get() {
738
+ var _info$ethAddress;
739
+ var info = this.authInfoManager.getAuthState();
740
+ return (_info$ethAddress = info.ethAddress) !== null && _info$ethAddress !== void 0 ? _info$ethAddress : null;
741
+ }
729
742
  }]);
730
743
  }();
731
744
  var LIVE_PUBLIC_KEY = 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEBIDHtLbgVM76SXZ4iuIjuO+ERQPnVpJzagOsZdYxFG3ZJmvfdpr/Z29SLUbdZWafrOlAVlKe1Ovf/tcH671tTw==';
@@ -781,6 +794,7 @@ var OCAuthSandbox = /*#__PURE__*/function (_OCAuthCore3) {
781
794
 
782
795
  "use strict";
783
796
  __webpack_require__.r(__webpack_exports__);
797
+ !(function webpackMissingModule() { var e = new Error("Cannot find module 'tiny-emitter'"); e.code = 'MODULE_NOT_FOUND'; throw e; }());
784
798
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
785
799
  function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
786
800
  function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
@@ -797,35 +811,48 @@ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e
797
811
  *
798
812
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
799
813
  */
814
+
815
+
816
+ var EVENT_AUTH_STATE_CHANGE = 'authStateChange';
800
817
  var AuthInfoManager = /*#__PURE__*/function () {
801
818
  function AuthInfoManager() {
802
819
  _classCallCheck(this, AuthInfoManager);
803
- _defineProperty(this, "_idInfo", void 0);
820
+ _defineProperty(this, "_emmitter", void 0);
821
+ _defineProperty(this, "_authState", void 0);
804
822
  this._authState = null;
805
- this._idInfo = null;
823
+ this._emitter = new !(function webpackMissingModule() { var e = new Error("Cannot find module 'tiny-emitter'"); e.code = 'MODULE_NOT_FOUND'; throw e; }())();
806
824
  }
807
825
  return _createClass(AuthInfoManager, [{
808
- key: "setIdInfo",
809
- value: function setIdInfo(IdInfo) {
810
- this._idInfo = Object.assign({}, IdInfo);
811
- }
812
- }, {
813
- key: "getIdInfoAttribute",
814
- value: function getIdInfoAttribute(attribute) {
815
- if (this._idInfo === null) {
816
- return undefined;
817
- }
818
- return this._idInfo[attribute];
826
+ key: "setAuthState",
827
+ value: function setAuthState(accessToken, idToken, OCId, ethAddress, isAuthenticated) {
828
+ this._authState = {
829
+ accessToken: accessToken,
830
+ idToken: idToken,
831
+ OCId: OCId,
832
+ ethAddress: ethAddress,
833
+ isAuthenticated: isAuthenticated
834
+ };
835
+ this._emitter.emit(EVENT_AUTH_STATE_CHANGE, this._authState);
819
836
  }
820
837
  }, {
821
- key: "getAuthInfo",
822
- value: function getAuthInfo() {
823
- return Object.assign({}, this._idInfo);
838
+ key: "getAuthState",
839
+ value: function getAuthState() {
840
+ return Object.assign({}, this._authState);
824
841
  }
825
842
  }, {
826
843
  key: "clear",
827
844
  value: function clear() {
828
- this._idInfo = null;
845
+ this._authState = null;
846
+ }
847
+ }, {
848
+ key: "subscribe",
849
+ value: function subscribe(handler) {
850
+ this._emitter.on(EVENT_AUTH_STATE_CHANGE, handler);
851
+ }
852
+ }, {
853
+ key: "unsubscribe",
854
+ value: function unsubscribe(handler) {
855
+ this._emitter.off(EVENT_AUTH_STATE_CHANGE, handler);
829
856
  }
830
857
  }]);
831
858
  }();
@@ -884,16 +911,27 @@ var TokenManager = /*#__PURE__*/function () {
884
911
  key: "exchangeTokenFromCode",
885
912
  value: function () {
886
913
  var _exchangeTokenFromCode = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(accessCode, codeVerifier) {
887
- var body, response, _yield$response$json, access_token, id_token, pubKey, tokenVerified, parsedAccessToken;
914
+ var state,
915
+ body,
916
+ response,
917
+ _yield$response$json,
918
+ access_token,
919
+ id_token,
920
+ pubKey,
921
+ tokenVerified,
922
+ parsedAccessToken,
923
+ storageData,
924
+ _args = arguments;
888
925
  return _regeneratorRuntime().wrap(function _callee$(_context) {
889
926
  while (1) switch (_context.prev = _context.next) {
890
927
  case 0:
928
+ state = _args.length > 2 && _args[2] !== undefined ? _args[2] : null;
891
929
  body = {
892
930
  accessCode: accessCode,
893
931
  codeVerifier: codeVerifier
894
932
  };
895
- _context.prev = 1;
896
- _context.next = 4;
933
+ _context.prev = 2;
934
+ _context.next = 5;
897
935
  return fetch(this.tokenEndPoint, {
898
936
  method: 'POST',
899
937
  headers: {
@@ -901,58 +939,66 @@ var TokenManager = /*#__PURE__*/function () {
901
939
  },
902
940
  body: JSON.stringify(body)
903
941
  });
904
- case 4:
942
+ case 5:
905
943
  response = _context.sent;
906
- _context.next = 7;
944
+ _context.next = 8;
907
945
  return response.json();
908
- case 7:
946
+ case 8:
909
947
  _yield$response$json = _context.sent;
910
948
  access_token = _yield$response$json.access_token;
911
949
  id_token = _yield$response$json.id_token;
912
950
  if (!(!access_token || !id_token)) {
913
- _context.next = 12;
951
+ _context.next = 13;
914
952
  break;
915
953
  }
916
954
  throw new _utils_errors__WEBPACK_IMPORTED_MODULE_2__["AuthError"]('Fail to exchange token');
917
- case 12:
918
- _context.next = 14;
955
+ case 13:
956
+ _context.next = 15;
919
957
  return this.getPublicKey();
920
- case 14:
958
+ case 15:
921
959
  pubKey = _context.sent;
922
- _context.next = 17;
960
+ _context.next = 18;
923
961
  return Object(_crypto__WEBPACK_IMPORTED_MODULE_1__["verifyToken"])(id_token, pubKey);
924
- case 17:
962
+ case 18:
925
963
  tokenVerified = _context.sent;
926
964
  if (tokenVerified) {
927
- _context.next = 20;
965
+ _context.next = 21;
928
966
  break;
929
967
  }
930
968
  throw new _utils_errors__WEBPACK_IMPORTED_MODULE_2__["AuthError"]('Unable to verify token');
931
- case 20:
969
+ case 21:
932
970
  parsedAccessToken = Object(_utils__WEBPACK_IMPORTED_MODULE_0__["parseJwt"])(access_token);
933
- this.storageManager.getStorageObject().setStorage({
971
+ storageData = Object.assign({
934
972
  access_token: access_token,
935
973
  id_token: id_token,
936
974
  expired: parsedAccessToken.exp
975
+ }, state && {
976
+ state: state
937
977
  });
938
- _context.next = 28;
978
+ this.storageManager.getStorageObject().setStorage(storageData);
979
+ _context.next = 30;
939
980
  break;
940
- case 24:
941
- _context.prev = 24;
942
- _context.t0 = _context["catch"](1);
981
+ case 26:
982
+ _context.prev = 26;
983
+ _context.t0 = _context["catch"](2);
943
984
  console.log(_context.t0);
944
985
  throw new _utils_errors__WEBPACK_IMPORTED_MODULE_2__["AuthError"]('Token acquisition failed');
945
- case 28:
986
+ case 30:
946
987
  case "end":
947
988
  return _context.stop();
948
989
  }
949
- }, _callee, this, [[1, 24]]);
990
+ }, _callee, this, [[2, 26]]);
950
991
  }));
951
992
  function exchangeTokenFromCode(_x, _x2) {
952
993
  return _exchangeTokenFromCode.apply(this, arguments);
953
994
  }
954
995
  return exchangeTokenFromCode;
955
996
  }()
997
+ }, {
998
+ key: "getStateParameter",
999
+ value: function getStateParameter() {
1000
+ return this.storageManager.getStorageObject().getItem('state');
1001
+ }
956
1002
  }, {
957
1003
  key: "getIdToken",
958
1004
  value: function getIdToken() {