@docyrus/signin 0.4.0 → 0.6.0

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,5 +1,5 @@
1
1
  import { MemoryOAuth2TokenStorage, OAuth2Client, RestApiClient, BrowserOAuth2TokenStorage } from '@docyrus/api-client';
2
- import { createContext, useState, useRef, useEffect, useMemo, useContext } from 'react';
2
+ import { createContext, useState, useRef, useEffect, useMemo, use } from 'react';
3
3
  import { jsx } from 'react/jsx-runtime';
4
4
 
5
5
  // src/react-native/rn-oauth2-auth.ts
@@ -75,6 +75,10 @@ var ReactNativeOAuth2Auth = class {
75
75
  async getStoredTokens() {
76
76
  return this.oauth2Client.getTokens();
77
77
  }
78
+ /** Persist externally obtained tokens for immediate authenticated use. */
79
+ async setTokens(tokens) {
80
+ await Promise.resolve(this.storage.setTokens(tokens));
81
+ }
78
82
  /** Check if the stored token is expired (with 60s buffer). */
79
83
  async isTokenExpired() {
80
84
  return this.oauth2Client.isTokenExpired();
@@ -200,6 +204,10 @@ var StandaloneOAuth2Auth = class {
200
204
  async getStoredTokens() {
201
205
  return this.oauth2Client.getTokens();
202
206
  }
207
+ /** Persist externally obtained tokens for immediate authenticated use. */
208
+ async setTokens(tokens) {
209
+ await Promise.resolve(this.storage.setTokens(tokens));
210
+ }
203
211
  /** Check if the stored token is expired (with 60s buffer). */
204
212
  async isTokenExpired() {
205
213
  return this.oauth2Client.isTokenExpired();
@@ -257,8 +265,8 @@ var IframeAuth = class {
257
265
  */
258
266
  requestTokenRefresh() {
259
267
  if (this.refreshPromise) {
268
+ const existing = this.refreshPromise;
260
269
  return new Promise((resolve, reject) => {
261
- const existing = this.refreshPromise;
262
270
  const originalResolve = existing.resolve;
263
271
  const originalReject = existing.reject;
264
272
  existing.resolve = (tokens) => {
@@ -343,6 +351,7 @@ var AuthManager = class {
343
351
  tokens = null;
344
352
  error = null;
345
353
  client = null;
354
+ user = null;
346
355
  standaloneAuth = null;
347
356
  iframeAuth = null;
348
357
  reactNativeAuth = null;
@@ -368,6 +377,13 @@ var AuthManager = class {
368
377
  getError() {
369
378
  return this.error;
370
379
  }
380
+ getUser() {
381
+ return this.user;
382
+ }
383
+ /** Re-fetch the current user from the API. No-op if not authenticated. */
384
+ async refreshUser() {
385
+ await this.fetchUser();
386
+ }
371
387
  subscribe(listener) {
372
388
  this.listeners.add(listener);
373
389
  return () => this.listeners.delete(listener);
@@ -377,13 +393,22 @@ var AuthManager = class {
377
393
  listener({
378
394
  status: this.status,
379
395
  tokens: this.tokens,
380
- error: this.error
396
+ error: this.error,
397
+ user: this.user
381
398
  });
382
399
  }
383
400
  }
401
+ getInitialTokens() {
402
+ return this.config.initialTokens ?? null;
403
+ }
384
404
  /** Initialize the auth manager. Must be called once on mount. */
385
405
  async initialize() {
386
406
  try {
407
+ if (this.mode === "iframe" && this.getInitialTokens()) {
408
+ throw new Error(
409
+ "initialTokens is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
410
+ );
411
+ }
387
412
  if (this.mode === "react-native") {
388
413
  await this.initializeReactNativeMode();
389
414
  } else if (this.mode === "iframe") {
@@ -416,6 +441,12 @@ var AuthManager = class {
416
441
  }
417
442
  return;
418
443
  }
444
+ const initialTokens = this.getInitialTokens();
445
+ if (initialTokens) {
446
+ await this.standaloneAuth.setTokens(initialTokens);
447
+ this.setAuthenticated(initialTokens);
448
+ return;
449
+ }
419
450
  const stored = await this.standaloneAuth.getStoredTokens();
420
451
  if (stored) {
421
452
  const isExpired = await this.standaloneAuth.isTokenExpired();
@@ -453,6 +484,12 @@ var AuthManager = class {
453
484
  */
454
485
  async initializeReactNativeMode() {
455
486
  this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
487
+ const initialTokens = this.getInitialTokens();
488
+ if (initialTokens) {
489
+ await this.reactNativeAuth.setTokens(initialTokens);
490
+ this.setAuthenticated(initialTokens);
491
+ return;
492
+ }
456
493
  const stored = await this.reactNativeAuth.getStoredTokens();
457
494
  if (stored) {
458
495
  const isExpired = await this.reactNativeAuth.isTokenExpired();
@@ -487,6 +524,30 @@ var AuthManager = class {
487
524
  if (this.mode !== "standalone" || !this.standaloneAuth) return;
488
525
  await this.standaloneAuth.initiateLogin();
489
526
  }
527
+ /**
528
+ * Bootstrap an authenticated session from tokens obtained outside the
529
+ * browser redirect flow, such as a prior device authorization flow.
530
+ */
531
+ async signInWithTokens(tokens) {
532
+ if (this.mode === "iframe") {
533
+ throw new Error(
534
+ "signInWithTokens() is not supported in iframe mode. Use the host postMessage signin flow or force standalone mode."
535
+ );
536
+ }
537
+ if (this.mode === "react-native") {
538
+ if (!this.reactNativeAuth) {
539
+ this.reactNativeAuth = new ReactNativeOAuth2Auth(this.config);
540
+ }
541
+ await this.reactNativeAuth.setTokens(tokens);
542
+ this.setAuthenticated(tokens);
543
+ return;
544
+ }
545
+ if (!this.standaloneAuth) {
546
+ this.standaloneAuth = new StandaloneOAuth2Auth(this.config);
547
+ }
548
+ await this.standaloneAuth.setTokens(tokens);
549
+ this.setAuthenticated(tokens);
550
+ }
490
551
  /**
491
552
  * Get the OAuth2 authorization URL without navigating.
492
553
  * Use this in Electron apps to open the URL in an external browser.
@@ -517,6 +578,7 @@ var AuthManager = class {
517
578
  }
518
579
  this.tokens = null;
519
580
  this.client = null;
581
+ this.user = null;
520
582
  this.status = "unauthenticated";
521
583
  this.error = null;
522
584
  this.notify();
@@ -524,6 +586,8 @@ var AuthManager = class {
524
586
  /**
525
587
  * Called when valid tokens are received (either mode).
526
588
  * Creates/updates the RestApiClient and schedules token refresh.
589
+ * Fires a user fetch in the background — the first notify() fires with user: null,
590
+ * and a second notify() fires once the user is fetched.
527
591
  */
528
592
  setAuthenticated(tokens) {
529
593
  this.tokens = tokens;
@@ -535,6 +599,18 @@ var AuthManager = class {
535
599
  this.createClient();
536
600
  this.scheduleTokenRefresh(tokens);
537
601
  this.notify();
602
+ this.fetchUser();
603
+ }
604
+ /** Fetch the current user from /v1/users/me. Silently sets user to null on failure. */
605
+ async fetchUser() {
606
+ if (!this.client) return;
607
+ try {
608
+ const response = await this.client.get("/v1/users/me");
609
+ this.user = response.data;
610
+ } catch {
611
+ this.user = null;
612
+ }
613
+ this.notify();
538
614
  }
539
615
  /**
540
616
  * Create a RestApiClient with a custom TokenManager that proactively
@@ -645,6 +721,106 @@ var AuthManager = class {
645
721
  this.listeners.clear();
646
722
  }
647
723
  };
724
+
725
+ // src/core/permissions.ts
726
+ var DEFAULT_ALWAYS_PERMITTED = {
727
+ "24ea9b34-4d74-11ef-bf16-6313ac30ce0e": [
728
+ "view",
729
+ "create",
730
+ "edit",
731
+ "delete"
732
+ ],
733
+ // report
734
+ "95406630-4d7d-11ef-a5cf-d7d8ab9d2310": [
735
+ "view",
736
+ "create",
737
+ "edit",
738
+ "delete"
739
+ ],
740
+ // report_widget
741
+ "996745ae-1744-11ef-a79c-abe22c3d5e97": ["view"],
742
+ // tenant_html_template
743
+ "0191e152-4619-7c08-bfc7-606f216d2757": ["view"],
744
+ // tenant_action_external_request_log
745
+ "01938bba-49ea-7b2f-8c09-adf14ab8c116": ["view"],
746
+ // tenant_data_source_child_removal_rule
747
+ "b413176e-175f-11ef-9df6-9f1f45cc8869": [
748
+ "view",
749
+ "create",
750
+ "edit",
751
+ "delete"
752
+ ],
753
+ // user_todo
754
+ "0191b75e-79cd-7344-93f3-81a3a3f52497": [
755
+ "view",
756
+ "create",
757
+ "edit",
758
+ "delete"
759
+ ],
760
+ // user_todo_list
761
+ "7756d784-175f-11ef-ac3b-0ba18bcdf569": [
762
+ "view",
763
+ "create",
764
+ "edit",
765
+ "delete"
766
+ ]
767
+ // user_note
768
+ };
769
+ var GLOBAL_EDITOR_OPERATIONS = /* @__PURE__ */ new Set([
770
+ "view",
771
+ "create",
772
+ "edit",
773
+ "delete",
774
+ "create_bulk",
775
+ "export",
776
+ "import",
777
+ "print"
778
+ ]);
779
+ function getAllRoles(user) {
780
+ if (!user) return [];
781
+ const roles = [];
782
+ if (user.primaryRole) {
783
+ roles.push(user.primaryRole);
784
+ }
785
+ if (user.roles?.length) {
786
+ for (const role of user.roles) {
787
+ if (!user.primaryRole || role.uid !== user.primaryRole.uid) {
788
+ roles.push(role);
789
+ }
790
+ }
791
+ }
792
+ return roles;
793
+ }
794
+ function hasRole(user, role) {
795
+ if (role == null) return true;
796
+ if (!user) return false;
797
+ const allRoles = getAllRoles(user);
798
+ if (allRoles.length === 0) return false;
799
+ if (Array.isArray(role)) {
800
+ if (role.length === 0) return true;
801
+ return allRoles.some((r) => role.includes(r.slug) || role.includes(r.uid));
802
+ }
803
+ return allRoles.some((r) => r.slug === role || r.uid === role);
804
+ }
805
+ function hasPermission(user, operation, dataSourceId, config) {
806
+ if (!user) return false;
807
+ if (hasRole(user, "super_admin")) return true;
808
+ if (dataSourceId && hasRole(user, "global_editor")) {
809
+ if (GLOBAL_EDITOR_OPERATIONS.has(operation)) return true;
810
+ }
811
+ if (dataSourceId && hasRole(user, "global_viewer")) {
812
+ if (operation === "view") return true;
813
+ }
814
+ if (dataSourceId) {
815
+ const alwaysPermitted = config?.alwaysPermittedDataSources ?? DEFAULT_ALWAYS_PERMITTED;
816
+ const permittedOps = alwaysPermitted[dataSourceId];
817
+ if (permittedOps?.includes(operation)) return true;
818
+ }
819
+ const rules = user.aclRules ?? [];
820
+ return rules.some(
821
+ (rule) => rule.dataSourceId === dataSourceId && rule.allowedOperations.includes(operation)
822
+ );
823
+ }
648
824
  var DocyrusAuthContext = createContext(null);
649
825
  function DocyrusAuthProvider({
650
826
  children,
@@ -653,18 +829,23 @@ function DocyrusAuthProvider({
653
829
  const [status, setStatus] = useState("loading");
654
830
  const [tokens, setTokens] = useState(null);
655
831
  const [client, setClient] = useState(null);
656
- const [mode, setMode] = useState(null);
657
832
  const [error, setError] = useState(null);
833
+ const [user, setUser] = useState(null);
834
+ const configRef = useRef(config);
658
835
  const managerRef = useRef(null);
836
+ if (!managerRef.current) {
837
+ managerRef.current = new AuthManager(configRef.current);
838
+ }
839
+ const mode = managerRef.current.getMode();
659
840
  useEffect(() => {
660
- const manager = new AuthManager(config);
661
- managerRef.current = manager;
662
- setMode(manager.getMode());
841
+ const manager = managerRef.current;
842
+ if (!manager) return;
663
843
  const unsubscribe = manager.subscribe((state) => {
664
844
  setStatus(state.status);
665
845
  setTokens(state.tokens);
666
846
  setError(state.error);
667
847
  setClient(manager.getClient());
848
+ setUser(state.user);
668
849
  });
669
850
  manager.initialize();
670
851
  return () => {
@@ -677,6 +858,11 @@ function DocyrusAuthProvider({
677
858
  managerRef.current?.signIn();
678
859
  };
679
860
  }, []);
861
+ const signInWithTokens = useMemo(() => {
862
+ return async (tokens2) => {
863
+ await managerRef.current?.signInWithTokens(tokens2);
864
+ };
865
+ }, []);
680
866
  const signOut = useMemo(() => {
681
867
  return async () => {
682
868
  await managerRef.current?.signOut();
@@ -687,29 +873,50 @@ function DocyrusAuthProvider({
687
873
  return managerRef.current?.getAuthorizationUrl() ?? null;
688
874
  };
689
875
  }, []);
876
+ const hasRole2 = useMemo(() => {
877
+ return (role) => hasRole(user, role);
878
+ }, [user]);
879
+ const hasPermission2 = useMemo(() => {
880
+ return (operation, dataSourceId) => hasPermission(user, operation, dataSourceId);
881
+ }, [user]);
882
+ const refreshUser = useMemo(() => {
883
+ return async () => {
884
+ await managerRef.current?.refreshUser();
885
+ };
886
+ }, []);
690
887
  const value = useMemo(() => ({
691
888
  status,
692
889
  mode,
693
890
  client,
694
891
  tokens,
892
+ user,
695
893
  signIn,
894
+ signInWithTokens,
696
895
  getAuthorizationUrl,
697
896
  signOut,
897
+ hasRole: hasRole2,
898
+ hasPermission: hasPermission2,
899
+ refreshUser,
698
900
  error
699
901
  }), [
700
902
  status,
701
903
  mode,
702
904
  client,
703
905
  tokens,
906
+ user,
704
907
  signIn,
908
+ signInWithTokens,
705
909
  getAuthorizationUrl,
706
910
  signOut,
911
+ hasRole2,
912
+ hasPermission2,
913
+ refreshUser,
707
914
  error
708
915
  ]);
709
- return /* @__PURE__ */ jsx(DocyrusAuthContext.Provider, { value, children });
916
+ return /* @__PURE__ */ jsx(DocyrusAuthContext, { value, children });
710
917
  }
711
918
  function useDocyrusAuth() {
712
- const context = useContext(DocyrusAuthContext);
919
+ const context = use(DocyrusAuthContext);
713
920
  if (!context) {
714
921
  throw new Error(
715
922
  "useDocyrusAuth must be used within a <DocyrusAuthProvider>. Wrap your app with <DocyrusAuthProvider> to provide auth context."
@@ -724,6 +931,6 @@ function useDocyrusClient() {
724
931
  return client;
725
932
  }
726
933
 
727
- export { AuthManager, DEFAULT_API_URL, DEFAULT_OAUTH_SCOPES, DocyrusAuthContext, DocyrusAuthProvider, ReactNativeOAuth2Auth, useDocyrusAuth, useDocyrusClient };
934
+ export { AuthManager, DEFAULT_API_URL, DEFAULT_OAUTH_SCOPES, DocyrusAuthContext, DocyrusAuthProvider, ReactNativeOAuth2Auth, getAllRoles, hasPermission, hasRole, useDocyrusAuth, useDocyrusClient };
728
935
  //# sourceMappingURL=index.js.map
729
936
  //# sourceMappingURL=index.js.map