nextauthz 1.0.9 → 1.1.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.
package/dist/index.d.mts CHANGED
@@ -1,13 +1,12 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { ReactNode } from 'react';
2
+ import * as React from 'react';
3
+ import React__default, { ReactNode } from 'react';
3
4
 
4
5
  type AuthContextType<UserType> = {
5
- user: UserType | null;
6
6
  login: (tokens: Record<string, string>, user: UserType) => void;
7
7
  logout: () => void;
8
8
  setUser: (user: UserType) => void;
9
9
  loading: boolean;
10
- error: Error | null;
11
10
  };
12
11
  type AuthContextOptions = {
13
12
  storage?: 'localStorage' | 'sessionStorage' | 'cookie';
@@ -22,8 +21,29 @@ declare function createAuthContext<UserType>(options?: AuthContextOptions): {
22
21
  useAuth: () => AuthContextType<UserType>;
23
22
  };
24
23
 
24
+ type AuthGuardProps = {
25
+ children: React__default.ReactNode;
26
+ redirectTo?: string;
27
+ tokenKey?: string;
28
+ refreshToken?: () => Promise<string | null>;
29
+ };
30
+ declare const AuthGuard: ({ children, redirectTo, tokenKey, refreshToken, }: AuthGuardProps) => react_jsx_runtime.JSX.Element | null;
31
+
32
+ type RoleGuardProps = {
33
+ children: React__default.ReactNode;
34
+ allowedRoles: string[];
35
+ redirectTo?: string;
36
+ };
37
+ declare const RoleGuard: React__default.FC<RoleGuardProps>;
38
+
25
39
  type User = {
26
40
  [key: string]: any;
27
41
  };
42
+ declare function createAppAuth(storage?: 'localStorage' | 'sessionStorage' | 'cookie'): {
43
+ AuthProvider: ({ children }: {
44
+ children: React.ReactNode;
45
+ }) => react_jsx_runtime.JSX.Element;
46
+ useAuth: () => AuthContextType<User>;
47
+ };
28
48
 
29
- export { type User, createAuthContext };
49
+ export { AuthGuard, RoleGuard, type User, createAppAuth, createAuthContext };
package/dist/index.d.ts CHANGED
@@ -1,13 +1,12 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { ReactNode } from 'react';
2
+ import * as React from 'react';
3
+ import React__default, { ReactNode } from 'react';
3
4
 
4
5
  type AuthContextType<UserType> = {
5
- user: UserType | null;
6
6
  login: (tokens: Record<string, string>, user: UserType) => void;
7
7
  logout: () => void;
8
8
  setUser: (user: UserType) => void;
9
9
  loading: boolean;
10
- error: Error | null;
11
10
  };
12
11
  type AuthContextOptions = {
13
12
  storage?: 'localStorage' | 'sessionStorage' | 'cookie';
@@ -22,8 +21,29 @@ declare function createAuthContext<UserType>(options?: AuthContextOptions): {
22
21
  useAuth: () => AuthContextType<UserType>;
23
22
  };
24
23
 
24
+ type AuthGuardProps = {
25
+ children: React__default.ReactNode;
26
+ redirectTo?: string;
27
+ tokenKey?: string;
28
+ refreshToken?: () => Promise<string | null>;
29
+ };
30
+ declare const AuthGuard: ({ children, redirectTo, tokenKey, refreshToken, }: AuthGuardProps) => react_jsx_runtime.JSX.Element | null;
31
+
32
+ type RoleGuardProps = {
33
+ children: React__default.ReactNode;
34
+ allowedRoles: string[];
35
+ redirectTo?: string;
36
+ };
37
+ declare const RoleGuard: React__default.FC<RoleGuardProps>;
38
+
25
39
  type User = {
26
40
  [key: string]: any;
27
41
  };
42
+ declare function createAppAuth(storage?: 'localStorage' | 'sessionStorage' | 'cookie'): {
43
+ AuthProvider: ({ children }: {
44
+ children: React.ReactNode;
45
+ }) => react_jsx_runtime.JSX.Element;
46
+ useAuth: () => AuthContextType<User>;
47
+ };
28
48
 
29
- export { type User, createAuthContext };
49
+ export { AuthGuard, RoleGuard, type User, createAppAuth, createAuthContext };
package/dist/index.js CHANGED
@@ -1699,18 +1699,18 @@ var require_react_jsx_runtime_development = __commonJS({
1699
1699
  function isValidElement(object) {
1700
1700
  return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
1701
1701
  }
1702
- var React2 = require_react(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
1702
+ var React4 = require_react(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React4.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
1703
1703
  return null;
1704
1704
  };
1705
- React2 = {
1705
+ React4 = {
1706
1706
  react_stack_bottom_frame: function(callStackForError) {
1707
1707
  return callStackForError();
1708
1708
  }
1709
1709
  };
1710
1710
  var specialPropKeyWarningShown;
1711
1711
  var didWarnAboutElementRef = {};
1712
- var unknownOwnerDebugStack = React2.react_stack_bottom_frame.bind(
1713
- React2,
1712
+ var unknownOwnerDebugStack = React4.react_stack_bottom_frame.bind(
1713
+ React4,
1714
1714
  UnknownOwner
1715
1715
  )();
1716
1716
  var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
@@ -1757,92 +1757,37 @@ var require_jsx_runtime = __commonJS({
1757
1757
  // src/index.ts
1758
1758
  var index_exports = {};
1759
1759
  __export(index_exports, {
1760
+ AuthGuard: () => AuthGuard_default,
1761
+ RoleGuard: () => RoleGuard_default,
1762
+ createAppAuth: () => createAppAuth,
1760
1763
  createAuthContext: () => createAuthContext
1761
1764
  });
1762
1765
  module.exports = __toCommonJS(index_exports);
1763
1766
 
1764
1767
  // src/AuthProvider.tsx
1765
1768
  var import_react = __toESM(require_react());
1766
- var import_react_token_manager = require("react-token-manager");
1767
-
1768
- // store/useGuardStore.ts
1769
- var import_zustand = require("zustand");
1770
- var useAuthStore = (0, import_zustand.create)((set) => ({
1771
- user: null,
1772
- isAuthenticated: false,
1773
- isAuthChecked: false,
1774
- error: null,
1775
- setUser: (user) => set({ user }),
1776
- setAuth: (isAuth) => set({ isAuthenticated: isAuth }),
1777
- setAuthChecked: (checked) => set({ isAuthChecked: checked }),
1778
- setError: (err) => set({ error: err }),
1779
- resetAuth: () => set({
1780
- user: null,
1781
- isAuthenticated: false,
1782
- isAuthChecked: false,
1783
- error: null
1784
- })
1785
- }));
1786
-
1787
- // src/AuthProvider.tsx
1788
1769
  var import_jsx_runtime = __toESM(require_jsx_runtime());
1789
1770
  function createAuthContext(options) {
1790
1771
  const AuthContext = (0, import_react.createContext)(null);
1791
1772
  const AuthProvider = ({ children }) => {
1792
- const storageType = options?.storage || "cookie";
1793
- (0, import_react.useEffect)(() => {
1794
- (0, import_react_token_manager.configureTokenManager)({ storage: storageType });
1795
- }, [storageType]);
1796
- const manager = (0, import_react_token_manager.useTokenManager)();
1797
1773
  const [loading, setLoading] = (0, import_react.useState)(true);
1798
- const rawUser = useAuthStore((state) => state.user);
1799
- const error = useAuthStore((state) => state.error);
1800
- const user = rawUser;
1801
- (0, import_react.useEffect)(() => {
1802
- const savedUser = manager.getSingleToken("user");
1803
- if (savedUser) {
1804
- try {
1805
- const parsedUser = JSON.parse(savedUser);
1806
- useAuthStore.getState().setUser(parsedUser);
1807
- useAuthStore.getState().setError(null);
1808
- } catch {
1809
- useAuthStore.getState().resetAuth();
1810
- useAuthStore.getState().setError(
1811
- new Error("Failed to parse saved user")
1812
- );
1813
- }
1814
- }
1815
- setLoading(false);
1816
- }, [manager]);
1817
1774
  const setUser = (userData) => {
1818
- useAuthStore.getState().setUser(userData);
1819
- useAuthStore.getState().setError(null);
1820
- manager.setTokens({ user: JSON.stringify(userData) });
1821
1775
  };
1822
1776
  const login = (tokens, userData) => {
1823
1777
  try {
1824
- manager.setTokens(tokens);
1825
1778
  setUser(userData);
1826
1779
  } catch (err) {
1827
- useAuthStore.getState().setError(
1828
- err instanceof Error ? err : new Error(String(err))
1829
- );
1830
1780
  }
1831
1781
  };
1832
1782
  const logout = () => {
1833
1783
  try {
1834
- manager.clearTokens();
1835
- useAuthStore.getState().resetAuth();
1836
1784
  } catch (err) {
1837
- useAuthStore.getState().setError(
1838
- err instanceof Error ? err : new Error(String(err))
1839
- );
1840
1785
  }
1841
1786
  };
1842
1787
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1843
1788
  AuthContext.Provider,
1844
1789
  {
1845
- value: { user, login, logout, setUser, loading, error },
1790
+ value: { login, logout, setUser, loading },
1846
1791
  children
1847
1792
  }
1848
1793
  );
@@ -1854,8 +1799,117 @@ function createAuthContext(options) {
1854
1799
  };
1855
1800
  return { AuthProvider, useAuth };
1856
1801
  }
1802
+
1803
+ // src/AuthGuard.tsx
1804
+ var import_react2 = __toESM(require_react());
1805
+ var import_navigation = require("next/navigation");
1806
+ var import_react_token_manager = require("react-token-manager");
1807
+
1808
+ // store/useGuardStore.ts
1809
+ var import_zustand = require("zustand");
1810
+ var useAuthStore = (0, import_zustand.create)((set) => ({
1811
+ user: null,
1812
+ isAuthenticated: false,
1813
+ isAuthChecked: false,
1814
+ error: null,
1815
+ setUser: (user) => set({ user }),
1816
+ setAuth: (isAuth) => set({ isAuthenticated: isAuth }),
1817
+ setAuthChecked: (checked) => set({ isAuthChecked: checked }),
1818
+ setError: (err) => set({ error: err }),
1819
+ resetAuth: () => set({
1820
+ user: null,
1821
+ isAuthenticated: false,
1822
+ isAuthChecked: false,
1823
+ error: null
1824
+ })
1825
+ }));
1826
+
1827
+ // src/AuthGuard.tsx
1828
+ var import_jsx_runtime2 = __toESM(require_jsx_runtime());
1829
+ var AuthGuard = ({
1830
+ children,
1831
+ redirectTo = "/login",
1832
+ tokenKey = "access_token",
1833
+ refreshToken
1834
+ }) => {
1835
+ const manager = (0, import_react_token_manager.useTokenManager)();
1836
+ const router = (0, import_navigation.useRouter)();
1837
+ const isAuthChecked = useAuthStore((state) => state.isAuthChecked);
1838
+ const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
1839
+ const error = useAuthStore((state) => state.error);
1840
+ (0, import_react2.useEffect)(() => {
1841
+ const checkAuth = async () => {
1842
+ try {
1843
+ let token = manager.getSingleToken(tokenKey);
1844
+ if (!token || manager.isExpired(token)) {
1845
+ if (refreshToken) {
1846
+ const newToken = await refreshToken();
1847
+ if (newToken) {
1848
+ manager.setTokens({ [tokenKey]: newToken });
1849
+ token = newToken;
1850
+ }
1851
+ }
1852
+ }
1853
+ const isValid = token && !manager.isExpired(token);
1854
+ useAuthStore.getState().setAuth(Boolean(isValid));
1855
+ if (!isValid) {
1856
+ router.replace(redirectTo);
1857
+ }
1858
+ } catch (err) {
1859
+ useAuthStore.getState().setError(err instanceof Error ? err : new Error(String(err)));
1860
+ useAuthStore.getState().setAuth(false);
1861
+ router.replace(redirectTo);
1862
+ } finally {
1863
+ useAuthStore.getState().setAuthChecked(true);
1864
+ }
1865
+ };
1866
+ checkAuth();
1867
+ }, [manager, router, redirectTo, tokenKey, refreshToken]);
1868
+ if (!isAuthChecked) return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { children: "Loading..." });
1869
+ if (error) return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1870
+ "Error: ",
1871
+ error.message
1872
+ ] });
1873
+ if (!isAuthenticated) return null;
1874
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children });
1875
+ };
1876
+ var AuthGuard_default = AuthGuard;
1877
+
1878
+ // src/RoleGuard.tsx
1879
+ var import_react3 = __toESM(require_react());
1880
+ var import_navigation2 = require("next/navigation");
1881
+
1882
+ // src/myAuth.ts
1883
+ var auth = createAppAuth();
1884
+
1885
+ // src/RoleGuard.tsx
1886
+ var import_jsx_runtime3 = __toESM(require_jsx_runtime());
1887
+ var RoleGuard = ({
1888
+ children,
1889
+ allowedRoles,
1890
+ redirectTo = "/unauthorized"
1891
+ }) => {
1892
+ const { useAuth } = auth;
1893
+ const { loading } = useAuth();
1894
+ const router = (0, import_navigation2.useRouter)();
1895
+ const [isChecking, setIsChecking] = (0, import_react3.useState)(true);
1896
+ (0, import_react3.useEffect)(() => {
1897
+ setIsChecking(false);
1898
+ }, [allowedRoles, redirectTo, router]);
1899
+ if (loading || isChecking) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: "Loading..." });
1900
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children });
1901
+ };
1902
+ var RoleGuard_default = RoleGuard;
1903
+
1904
+ // src/index.ts
1905
+ function createAppAuth(storage = "cookie") {
1906
+ return createAuthContext({ storage });
1907
+ }
1857
1908
  // Annotate the CommonJS export names for ESM import in node:
1858
1909
  0 && (module.exports = {
1910
+ AuthGuard,
1911
+ RoleGuard,
1912
+ createAppAuth,
1859
1913
  createAuthContext
1860
1914
  });
1861
1915
  /*! Bundled license information:
package/dist/index.mjs CHANGED
@@ -1693,18 +1693,18 @@ var require_react_jsx_runtime_development = __commonJS({
1693
1693
  function isValidElement(object) {
1694
1694
  return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
1695
1695
  }
1696
- var React2 = require_react(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
1696
+ var React4 = require_react(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React4.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
1697
1697
  return null;
1698
1698
  };
1699
- React2 = {
1699
+ React4 = {
1700
1700
  react_stack_bottom_frame: function(callStackForError) {
1701
1701
  return callStackForError();
1702
1702
  }
1703
1703
  };
1704
1704
  var specialPropKeyWarningShown;
1705
1705
  var didWarnAboutElementRef = {};
1706
- var unknownOwnerDebugStack = React2.react_stack_bottom_frame.bind(
1707
- React2,
1706
+ var unknownOwnerDebugStack = React4.react_stack_bottom_frame.bind(
1707
+ React4,
1708
1708
  UnknownOwner
1709
1709
  )();
1710
1710
  var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
@@ -1750,86 +1750,28 @@ var require_jsx_runtime = __commonJS({
1750
1750
 
1751
1751
  // src/AuthProvider.tsx
1752
1752
  var import_react = __toESM(require_react());
1753
- import { configureTokenManager, useTokenManager } from "react-token-manager";
1754
-
1755
- // store/useGuardStore.ts
1756
- import { create } from "zustand";
1757
- var useAuthStore = create((set) => ({
1758
- user: null,
1759
- isAuthenticated: false,
1760
- isAuthChecked: false,
1761
- error: null,
1762
- setUser: (user) => set({ user }),
1763
- setAuth: (isAuth) => set({ isAuthenticated: isAuth }),
1764
- setAuthChecked: (checked) => set({ isAuthChecked: checked }),
1765
- setError: (err) => set({ error: err }),
1766
- resetAuth: () => set({
1767
- user: null,
1768
- isAuthenticated: false,
1769
- isAuthChecked: false,
1770
- error: null
1771
- })
1772
- }));
1773
-
1774
- // src/AuthProvider.tsx
1775
1753
  var import_jsx_runtime = __toESM(require_jsx_runtime());
1776
1754
  function createAuthContext(options) {
1777
1755
  const AuthContext = (0, import_react.createContext)(null);
1778
1756
  const AuthProvider = ({ children }) => {
1779
- const storageType = options?.storage || "cookie";
1780
- (0, import_react.useEffect)(() => {
1781
- configureTokenManager({ storage: storageType });
1782
- }, [storageType]);
1783
- const manager = useTokenManager();
1784
1757
  const [loading, setLoading] = (0, import_react.useState)(true);
1785
- const rawUser = useAuthStore((state) => state.user);
1786
- const error = useAuthStore((state) => state.error);
1787
- const user = rawUser;
1788
- (0, import_react.useEffect)(() => {
1789
- const savedUser = manager.getSingleToken("user");
1790
- if (savedUser) {
1791
- try {
1792
- const parsedUser = JSON.parse(savedUser);
1793
- useAuthStore.getState().setUser(parsedUser);
1794
- useAuthStore.getState().setError(null);
1795
- } catch {
1796
- useAuthStore.getState().resetAuth();
1797
- useAuthStore.getState().setError(
1798
- new Error("Failed to parse saved user")
1799
- );
1800
- }
1801
- }
1802
- setLoading(false);
1803
- }, [manager]);
1804
1758
  const setUser = (userData) => {
1805
- useAuthStore.getState().setUser(userData);
1806
- useAuthStore.getState().setError(null);
1807
- manager.setTokens({ user: JSON.stringify(userData) });
1808
1759
  };
1809
1760
  const login = (tokens, userData) => {
1810
1761
  try {
1811
- manager.setTokens(tokens);
1812
1762
  setUser(userData);
1813
1763
  } catch (err) {
1814
- useAuthStore.getState().setError(
1815
- err instanceof Error ? err : new Error(String(err))
1816
- );
1817
1764
  }
1818
1765
  };
1819
1766
  const logout = () => {
1820
1767
  try {
1821
- manager.clearTokens();
1822
- useAuthStore.getState().resetAuth();
1823
1768
  } catch (err) {
1824
- useAuthStore.getState().setError(
1825
- err instanceof Error ? err : new Error(String(err))
1826
- );
1827
1769
  }
1828
1770
  };
1829
1771
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1830
1772
  AuthContext.Provider,
1831
1773
  {
1832
- value: { user, login, logout, setUser, loading, error },
1774
+ value: { login, logout, setUser, loading },
1833
1775
  children
1834
1776
  }
1835
1777
  );
@@ -1841,7 +1783,116 @@ function createAuthContext(options) {
1841
1783
  };
1842
1784
  return { AuthProvider, useAuth };
1843
1785
  }
1786
+
1787
+ // src/AuthGuard.tsx
1788
+ var import_react2 = __toESM(require_react());
1789
+ import { useRouter } from "next/navigation";
1790
+ import { useTokenManager } from "react-token-manager";
1791
+
1792
+ // store/useGuardStore.ts
1793
+ import { create } from "zustand";
1794
+ var useAuthStore = create((set) => ({
1795
+ user: null,
1796
+ isAuthenticated: false,
1797
+ isAuthChecked: false,
1798
+ error: null,
1799
+ setUser: (user) => set({ user }),
1800
+ setAuth: (isAuth) => set({ isAuthenticated: isAuth }),
1801
+ setAuthChecked: (checked) => set({ isAuthChecked: checked }),
1802
+ setError: (err) => set({ error: err }),
1803
+ resetAuth: () => set({
1804
+ user: null,
1805
+ isAuthenticated: false,
1806
+ isAuthChecked: false,
1807
+ error: null
1808
+ })
1809
+ }));
1810
+
1811
+ // src/AuthGuard.tsx
1812
+ var import_jsx_runtime2 = __toESM(require_jsx_runtime());
1813
+ var AuthGuard = ({
1814
+ children,
1815
+ redirectTo = "/login",
1816
+ tokenKey = "access_token",
1817
+ refreshToken
1818
+ }) => {
1819
+ const manager = useTokenManager();
1820
+ const router = useRouter();
1821
+ const isAuthChecked = useAuthStore((state) => state.isAuthChecked);
1822
+ const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
1823
+ const error = useAuthStore((state) => state.error);
1824
+ (0, import_react2.useEffect)(() => {
1825
+ const checkAuth = async () => {
1826
+ try {
1827
+ let token = manager.getSingleToken(tokenKey);
1828
+ if (!token || manager.isExpired(token)) {
1829
+ if (refreshToken) {
1830
+ const newToken = await refreshToken();
1831
+ if (newToken) {
1832
+ manager.setTokens({ [tokenKey]: newToken });
1833
+ token = newToken;
1834
+ }
1835
+ }
1836
+ }
1837
+ const isValid = token && !manager.isExpired(token);
1838
+ useAuthStore.getState().setAuth(Boolean(isValid));
1839
+ if (!isValid) {
1840
+ router.replace(redirectTo);
1841
+ }
1842
+ } catch (err) {
1843
+ useAuthStore.getState().setError(err instanceof Error ? err : new Error(String(err)));
1844
+ useAuthStore.getState().setAuth(false);
1845
+ router.replace(redirectTo);
1846
+ } finally {
1847
+ useAuthStore.getState().setAuthChecked(true);
1848
+ }
1849
+ };
1850
+ checkAuth();
1851
+ }, [manager, router, redirectTo, tokenKey, refreshToken]);
1852
+ if (!isAuthChecked) return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { children: "Loading..." });
1853
+ if (error) return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { children: [
1854
+ "Error: ",
1855
+ error.message
1856
+ ] });
1857
+ if (!isAuthenticated) return null;
1858
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children });
1859
+ };
1860
+ var AuthGuard_default = AuthGuard;
1861
+
1862
+ // src/RoleGuard.tsx
1863
+ var import_react3 = __toESM(require_react());
1864
+ import { useRouter as useRouter2 } from "next/navigation";
1865
+
1866
+ // src/myAuth.ts
1867
+ var auth = createAppAuth();
1868
+
1869
+ // src/RoleGuard.tsx
1870
+ var import_jsx_runtime3 = __toESM(require_jsx_runtime());
1871
+ var RoleGuard = ({
1872
+ children,
1873
+ allowedRoles,
1874
+ redirectTo = "/unauthorized"
1875
+ }) => {
1876
+ const { useAuth } = auth;
1877
+ const { loading } = useAuth();
1878
+ const router = useRouter2();
1879
+ const [isChecking, setIsChecking] = (0, import_react3.useState)(true);
1880
+ (0, import_react3.useEffect)(() => {
1881
+ setIsChecking(false);
1882
+ }, [allowedRoles, redirectTo, router]);
1883
+ if (loading || isChecking) return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { children: "Loading..." });
1884
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children });
1885
+ };
1886
+ var RoleGuard_default = RoleGuard;
1887
+
1888
+ // src/index.ts
1889
+ function createAppAuth(storage = "cookie") {
1890
+ return createAuthContext({ storage });
1891
+ }
1844
1892
  export {
1893
+ AuthGuard_default as AuthGuard,
1894
+ RoleGuard_default as RoleGuard,
1895
+ createAppAuth,
1845
1896
  createAuthContext
1846
1897
  };
1847
1898
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nextauthz",
3
- "version": "1.0.9",
3
+ "version": "1.1.1",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
package/src/AuthGuard.tsx CHANGED
@@ -1,67 +1,67 @@
1
- // 'use client'
1
+ 'use client'
2
2
 
3
- // import React, { useEffect, useState } from 'react'
4
- // import { useRouter } from 'next/navigation'
5
- // import { useTokenManager } from 'react-token-manager'
6
- // import { useAuthStore } from '../store/useGuardStore'
3
+ import React, { useEffect, useState } from 'react'
4
+ import { useRouter } from 'next/navigation'
5
+ import { useTokenManager } from 'react-token-manager'
6
+ import { useAuthStore } from '../store/useGuardStore'
7
7
 
8
- // type AuthGuardProps = {
9
- // children: React.ReactNode
10
- // redirectTo?: string
11
- // tokenKey?: string
12
- // refreshToken?: () => Promise<string | null>
13
- // }
8
+ type AuthGuardProps = {
9
+ children: React.ReactNode
10
+ redirectTo?: string
11
+ tokenKey?: string
12
+ refreshToken?: () => Promise<string | null>
13
+ }
14
14
 
15
- // const AuthGuard = ({
16
- // children,
17
- // redirectTo = '/login',
18
- // tokenKey = 'access_token',
19
- // refreshToken,
20
- // }: AuthGuardProps) => {
21
- // const manager = useTokenManager()
22
- // const router = useRouter()
23
- // const isAuthChecked = useAuthStore((state) => state.isAuthChecked)
24
- // const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
25
- // const error = useAuthStore((state) => state.error)
15
+ const AuthGuard = ({
16
+ children,
17
+ redirectTo = '/login',
18
+ tokenKey = 'access_token',
19
+ refreshToken,
20
+ }: AuthGuardProps) => {
21
+ const manager = useTokenManager()
22
+ const router = useRouter()
23
+ const isAuthChecked = useAuthStore((state) => state.isAuthChecked)
24
+ const isAuthenticated = useAuthStore((state) => state.isAuthenticated)
25
+ const error = useAuthStore((state) => state.error)
26
26
 
27
- // useEffect(() => {
28
- // const checkAuth = async () => {
29
- // try {
30
- // let token = manager.getSingleToken(tokenKey)
27
+ useEffect(() => {
28
+ const checkAuth = async () => {
29
+ try {
30
+ let token = manager.getSingleToken(tokenKey)
31
31
 
32
- // if (!token || manager.isExpired(token)) {
33
- // if (refreshToken) {
34
- // const newToken = await refreshToken()
35
- // if (newToken) {
36
- // manager.setTokens({ [tokenKey]: newToken })
37
- // token = newToken
38
- // }
39
- // }
40
- // }
32
+ if (!token || manager.isExpired(token)) {
33
+ if (refreshToken) {
34
+ const newToken = await refreshToken()
35
+ if (newToken) {
36
+ manager.setTokens({ [tokenKey]: newToken })
37
+ token = newToken
38
+ }
39
+ }
40
+ }
41
41
 
42
- // const isValid = token && !manager.isExpired(token)
43
- // useAuthStore.getState().setAuth(Boolean(isValid))
42
+ const isValid = token && !manager.isExpired(token)
43
+ useAuthStore.getState().setAuth(Boolean(isValid))
44
44
 
45
- // if (!isValid) {
46
- // router.replace(redirectTo)
47
- // }
48
- // } catch (err: any) {
49
- // useAuthStore.getState().setError(err instanceof Error ? err : new Error(String(err)))
50
- // useAuthStore.getState().setAuth(false)
51
- // router.replace(redirectTo)
52
- // } finally {
53
- // useAuthStore.getState().setAuthChecked(true)
54
- // }
55
- // }
45
+ if (!isValid) {
46
+ router.replace(redirectTo)
47
+ }
48
+ } catch (err: any) {
49
+ useAuthStore.getState().setError(err instanceof Error ? err : new Error(String(err)))
50
+ useAuthStore.getState().setAuth(false)
51
+ router.replace(redirectTo)
52
+ } finally {
53
+ useAuthStore.getState().setAuthChecked(true)
54
+ }
55
+ }
56
56
 
57
- // checkAuth()
58
- // }, [manager, router, redirectTo, tokenKey, refreshToken])
57
+ checkAuth()
58
+ }, [manager, router, redirectTo, tokenKey, refreshToken])
59
59
 
60
- // if (!isAuthChecked) return <div>Loading...</div>
61
- // if (error) return <div>Error: {error.message}</div>
62
- // if (!isAuthenticated) return null
60
+ if (!isAuthChecked) return <div>Loading...</div>
61
+ if (error) return <div>Error: {error.message}</div>
62
+ if (!isAuthenticated) return null
63
63
 
64
- // return <>{children}</>
65
- // }
64
+ return <>{children}</>
65
+ }
66
66
 
67
- // export default AuthGuard
67
+ export default AuthGuard
@@ -7,16 +7,15 @@ import React, {
7
7
  useEffect,
8
8
  useState,
9
9
  } from 'react'
10
- import { configureTokenManager, useTokenManager } from 'react-token-manager'
11
- import { useAuthStore } from '../store/useGuardStore'
10
+ // import { configureTokenManager, useTokenManager } from 'react-token-manager'
11
+ // import { useAuthStore } from '../store/useGuardStore'
12
12
 
13
13
  export type AuthContextType<UserType> = {
14
- user: UserType | null
14
+
15
15
  login: (tokens: Record<string, string>, user: UserType) => void
16
16
  logout: () => void
17
17
  setUser: (user: UserType) => void
18
18
  loading: boolean
19
- error: Error | null
20
19
  }
21
20
 
22
21
  export type AuthContextOptions = {
@@ -30,71 +29,71 @@ export function createAuthContext<UserType>(options?: AuthContextOptions) {
30
29
  const AuthContext = createContext<AuthContextType<UserType> | null>(null)
31
30
 
32
31
  const AuthProvider = ({ children }: { children: ReactNode }) => {
33
- const storageType = options?.storage || 'cookie'
32
+ // const storageType = options?.storage || 'cookie'
34
33
 
35
34
  // Configure token manager once on mount
36
- useEffect(() => {
37
- configureTokenManager({ storage: storageType })
38
- }, [storageType])
35
+ // useEffect(() => {
36
+ // configureTokenManager({ storage: storageType })
37
+ // }, [storageType])
39
38
 
40
39
  // ✅ Hooks must be called inside component
41
- const manager = useTokenManager()
40
+ // const manager = useTokenManager()
42
41
 
43
42
  const [loading, setLoading] = useState(true)
44
43
 
45
- const rawUser = useAuthStore((state) => state.user)
46
- const error = useAuthStore((state) => state.error)
47
- const user = rawUser as UserType | null
44
+ // const rawUser = useAuthStore((state) => state.user)
45
+ // const error = useAuthStore((state) => state.error)
46
+ // const user = rawUser as UserType | null
48
47
 
49
48
  // Restore saved user from token manager
50
- useEffect(() => {
51
- const savedUser = manager.getSingleToken('user')
52
- if (savedUser) {
53
- try {
54
- const parsedUser = JSON.parse(savedUser)
55
- useAuthStore.getState().setUser(parsedUser)
56
- useAuthStore.getState().setError(null)
57
- } catch {
58
- useAuthStore.getState().resetAuth()
59
- useAuthStore.getState().setError(
60
- new Error('Failed to parse saved user')
61
- )
62
- }
63
- }
64
- setLoading(false)
65
- }, [manager])
49
+ // useEffect(() => {
50
+ // const savedUser = manager.getSingleToken('user')
51
+ // if (savedUser) {
52
+ // try {
53
+ // const parsedUser = JSON.parse(savedUser)
54
+ // useAuthStore.getState().setUser(parsedUser)
55
+ // useAuthStore.getState().setError(null)
56
+ // } catch {
57
+ // useAuthStore.getState().resetAuth()
58
+ // useAuthStore.getState().setError(
59
+ // new Error('Failed to parse saved user')
60
+ // )
61
+ // }
62
+ // }
63
+ // setLoading(false)
64
+ // }, [manager])
66
65
 
67
66
  const setUser = (userData: UserType) => {
68
- useAuthStore.getState().setUser(userData as any)
69
- useAuthStore.getState().setError(null)
70
- manager.setTokens({ user: JSON.stringify(userData) })
67
+ // useAuthStore.getState().setUser(userData as any)
68
+ // useAuthStore.getState().setError(null)
69
+ // manager.setTokens({ user: JSON.stringify(userData) })
71
70
  }
72
71
 
73
72
  const login = (tokens: Record<string, string>, userData: UserType) => {
74
73
  try {
75
- manager.setTokens(tokens)
74
+ // manager.setTokens(tokens)
76
75
  setUser(userData)
77
76
  } catch (err) {
78
- useAuthStore.getState().setError(
79
- err instanceof Error ? err : new Error(String(err))
80
- )
77
+ // useAuthStore.getState().setError(
78
+ // err instanceof Error ? err : new Error(String(err))
79
+ // )
81
80
  }
82
81
  }
83
82
 
84
83
  const logout = () => {
85
84
  try {
86
- manager.clearTokens()
87
- useAuthStore.getState().resetAuth()
85
+ // manager.clearTokens()
86
+ // useAuthStore.getState().resetAuth()
88
87
  } catch (err) {
89
- useAuthStore.getState().setError(
90
- err instanceof Error ? err : new Error(String(err))
91
- )
88
+ // useAuthStore.getState().setError(
89
+ // err instanceof Error ? err : new Error(String(err))
90
+ // )
92
91
  }
93
92
  }
94
93
 
95
94
  return (
96
95
  <AuthContext.Provider
97
- value={{ user, login, logout, setUser, loading, error }}
96
+ value={{ login, logout, setUser, loading }}
98
97
  >
99
98
  {children}
100
99
  </AuthContext.Provider>
package/src/RoleGuard.tsx CHANGED
@@ -1,40 +1,40 @@
1
- // 'use client'
2
-
3
- // import React, { useEffect, useState } from 'react'
4
- // import { useRouter } from 'next/navigation'
5
- // import { auth } from './myAuth'
6
-
7
- // type RoleGuardProps = {
8
- // children: React.ReactNode
9
- // allowedRoles: string[]
10
- // redirectTo?: string
11
- // }
12
-
13
- // const RoleGuard: React.FC<RoleGuardProps> = ({
14
- // children,
15
- // allowedRoles,
16
- // redirectTo = '/unauthorized',
17
- // }) => {
18
- // // ✅ Destructure useAuth INSIDE the component
19
- // const { useAuth } = auth
20
- // const { user, loading } = useAuth()
21
-
22
- // const router = useRouter()
23
- // const [isChecking, setIsChecking] = useState(true)
24
-
25
- // useEffect(() => {
26
- // if (!user) return
27
-
28
- // const hasAccess = allowedRoles.includes(user?.role)
29
- // if (!hasAccess) {
30
- // router.replace(redirectTo)
31
- // }
32
- // setIsChecking(false)
33
- // }, [user, allowedRoles, redirectTo, router])
34
-
35
- // if (loading || !user || isChecking) return <div>Loading...</div>
36
-
37
- // return <>{children}</>
38
- // }
39
-
40
- // export default RoleGuard
1
+ 'use client'
2
+
3
+ import React, { useEffect, useState } from 'react'
4
+ import { useRouter } from 'next/navigation'
5
+ import { auth } from './myAuth'
6
+
7
+ type RoleGuardProps = {
8
+ children: React.ReactNode
9
+ allowedRoles: string[]
10
+ redirectTo?: string
11
+ }
12
+
13
+ const RoleGuard: React.FC<RoleGuardProps> = ({
14
+ children,
15
+ allowedRoles,
16
+ redirectTo = '/unauthorized',
17
+ }) => {
18
+ // ✅ Destructure useAuth INSIDE the component
19
+ const { useAuth } = auth
20
+ const { loading } = useAuth()
21
+
22
+ const router = useRouter()
23
+ const [isChecking, setIsChecking] = useState(true)
24
+
25
+ useEffect(() => {
26
+ // if (!user) return
27
+
28
+ // const hasAccess = allowedRoles.includes(user?.role)
29
+ // if (!hasAccess) {
30
+ // router.replace(redirectTo)
31
+ // }
32
+ setIsChecking(false)
33
+ }, [allowedRoles, redirectTo, router])
34
+
35
+ if (loading || isChecking) return <div>Loading...</div>
36
+
37
+ return <>{children}</>
38
+ }
39
+
40
+ export default RoleGuard
package/src/index.ts CHANGED
@@ -5,12 +5,12 @@ export type User = {
5
5
  }
6
6
 
7
7
  // Export factory instead of fixed instance
8
- // export function createAppAuth(
9
- // storage: 'localStorage' | 'sessionStorage' | 'cookie' = 'cookie'
10
- // ) {
11
- // return createAuthContext<User>({ storage })
12
- // }
8
+ export function createAppAuth(
9
+ storage: 'localStorage' | 'sessionStorage' | 'cookie' = 'cookie'
10
+ ) {
11
+ return createAuthContext<User>({ storage })
12
+ }
13
13
 
14
14
  export { createAuthContext } from './AuthProvider'
15
- // export { default as AuthGuard } from './AuthGuard'
16
- // export { default as RoleGuard } from './RoleGuard'
15
+ export { default as AuthGuard } from './AuthGuard'
16
+ export { default as RoleGuard } from './RoleGuard'
package/src/myAuth.ts CHANGED
@@ -1,4 +1,4 @@
1
- // // myAuth.ts
2
- // 'use client'
3
- // import { createAppAuth } from '.'
4
- // export const auth = createAppAuth() // { AuthProvider, useAuth }
1
+ // myAuth.ts
2
+ 'use client'
3
+ import { createAppAuth } from '.'
4
+ export const auth = createAppAuth() // { AuthProvider, useAuth }