@plyaz/auth 1.0.3 → 1.0.4

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/commits.txt CHANGED
@@ -1,2 +1 @@
1
- - chore: Update types (usmangq12)
2
- - chore: Shft all types to types package (usmangq12)
1
+ - chore: Update hooks (usmangq12)
package/dist/index.cjs CHANGED
@@ -15,6 +15,7 @@ var supabaseJs = require('@supabase/supabase-js');
15
15
  var buffer = require('buffer');
16
16
  var zustand = require('zustand');
17
17
  var middleware = require('zustand/middleware');
18
+ var nextjs = require('@clerk/nextjs');
18
19
  var jsxRuntime = require('react/jsx-runtime');
19
20
  var react = require('react');
20
21
 
@@ -5031,6 +5032,7 @@ var useAuthStore = zustand.create()(
5031
5032
  const { permissions } = get();
5032
5033
  return permissions.includes(permission);
5033
5034
  }, "hasPermission"),
5035
+ // setSession : ()=>set({isAuthenticated:true}),
5034
5036
  hasRole: /* @__PURE__ */ __name((role) => {
5035
5037
  const { roles } = get();
5036
5038
  return roles.includes(role);
@@ -5134,72 +5136,137 @@ var useAuthStore = zustand.create()(
5134
5136
  )
5135
5137
  )
5136
5138
  );
5137
-
5138
- // src/client/utils/handleAuthAction.ts
5139
- var handleAuthAction = /* @__PURE__ */ __name(async (action) => {
5140
- const store = useAuthStore();
5141
- store.setLoading(true);
5142
- store.setError(null);
5143
- try {
5144
- const result = await action();
5145
- return result;
5146
- } catch (err) {
5147
- const errorMessage = err instanceof Error ? err.message : "Authentication failed";
5148
- store.setError(errorMessage);
5149
- throw err;
5150
- } finally {
5151
- store.setLoading(false);
5152
- }
5153
- }, "handleAuthAction");
5154
-
5155
- // src/client/utils/createAuthContextValues.ts
5156
- var createAuthContextValue = /* @__PURE__ */ __name(() => {
5157
- const store = useAuthStore();
5139
+ var useClerkAuthClient = /* @__PURE__ */ __name(() => {
5140
+ const { signIn, isLoaded: signInLoaded } = nextjs.useSignIn();
5141
+ const { user: clerkUser, isLoaded: userLoaded } = nextjs.useUser();
5142
+ const { signOut } = nextjs.useClerk();
5143
+ const executeAuth = /* @__PURE__ */ __name(async (provider, redirectPath) => {
5144
+ if (!signIn) return;
5145
+ switch (provider) {
5146
+ case "GOOGLE":
5147
+ case "FACEBOOK":
5148
+ return signIn.authenticateWithRedirect({
5149
+ strategy: provider === "GOOGLE" ? "oauth_google" : "oauth_facebook",
5150
+ redirectUrl: "/sso-callback",
5151
+ redirectUrlComplete: redirectPath
5152
+ });
5153
+ case "METAMASK":
5154
+ return signIn.authenticateWithMetamask();
5155
+ case "COINBASE":
5156
+ return signIn.authenticateWithCoinbaseWallet();
5157
+ case "EMAIL":
5158
+ throw new Error("Email auth requires an identifier from your form.");
5159
+ default:
5160
+ throw new Error(`Unsupported provider: ${provider}`);
5161
+ }
5162
+ }, "executeAuth");
5163
+ const mappedUser = clerkUser ? {
5164
+ id: clerkUser.id,
5165
+ // Primary ID used in your app
5166
+ clerkUserId: clerkUser.id,
5167
+ // Optional reference specifically for Clerk
5168
+ email: clerkUser.primaryEmailAddress?.emailAddress ?? "",
5169
+ authProvider: clerkUser.publicMetadata?.provider ?? "clerk",
5170
+ firstName: clerkUser.firstName ?? void 0,
5171
+ lastName: clerkUser.lastName ?? void 0,
5172
+ displayName: clerkUser.fullName ?? clerkUser.primaryEmailAddress?.emailAddress ?? "User",
5173
+ avatarUrl: clerkUser.imageUrl,
5174
+ phoneNumber: clerkUser.primaryPhoneNumber?.phoneNumber ?? void 0,
5175
+ isActive: true,
5176
+ // If they can log in, they are active
5177
+ isVerified: clerkUser.primaryEmailAddress?.verification.status === "verified",
5178
+ createdAt: clerkUser.createdAt ?? /* @__PURE__ */ new Date(),
5179
+ updatedAt: clerkUser.updatedAt ?? /* @__PURE__ */ new Date(),
5180
+ lastLoginAt: clerkUser.lastSignInAt ?? void 0,
5181
+ roles: clerkUser.publicMetadata?.roles ?? [],
5182
+ isSuspended: clerkUser.publicMetadata?.isSuspended ?? false,
5183
+ // Password hash is never exposed on the client side for security
5184
+ passwordHash: void 0
5185
+ } : null;
5158
5186
  return {
5159
- user: store.user,
5160
- isAuthenticated: store.isAuthenticated,
5161
- isLoading: store.isLoading,
5162
- error: store.error,
5163
- signIn: /* @__PURE__ */ __name(async (provider, credentials) => {
5164
- return handleAuthAction(() => store.signIn(provider, credentials));
5187
+ user: mappedUser ?? null,
5188
+ isAuthenticated: !!clerkUser,
5189
+ isLoading: !signInLoaded || !userLoaded,
5190
+ signIn: /* @__PURE__ */ __name(async (provider) => {
5191
+ await executeAuth(provider, "/dashboard");
5165
5192
  }, "signIn"),
5166
- signUp: /* @__PURE__ */ __name(async (provider, data) => {
5167
- return handleAuthAction(() => store.signUp(provider, data));
5193
+ signUp: /* @__PURE__ */ __name(async (provider) => {
5194
+ await executeAuth(provider, "/onboarding");
5168
5195
  }, "signUp"),
5169
5196
  signOut: /* @__PURE__ */ __name(async () => {
5170
- return handleAuthAction(() => store.signOut());
5197
+ await signOut();
5171
5198
  }, "signOut"),
5172
- linkAccount: /* @__PURE__ */ __name(async (userId, provider, data) => {
5173
- return handleAuthAction(async () => {
5174
- const connectedAccount = {
5175
- ...data,
5176
- userId,
5177
- provider,
5178
- providerType: "",
5179
- providerAccountId: "",
5180
- isPrimary: false,
5181
- isVerified: false,
5182
- isActive: false,
5183
- linkedAt: /* @__PURE__ */ new Date(),
5184
- createdAt: /* @__PURE__ */ new Date(),
5185
- updatedAt: /* @__PURE__ */ new Date()
5186
- };
5187
- store.addConnectedAccount(connectedAccount);
5188
- return connectedAccount;
5199
+ linkAccount: /* @__PURE__ */ __name(async (provider) => {
5200
+ if (!clerkUser) throw new Error("Must be logged in to link accounts");
5201
+ const strategyMapping = {
5202
+ GOOGLE: "oauth_google",
5203
+ FACEBOOK: "oauth_facebook",
5204
+ METAMASK: "web3_metamask_signature",
5205
+ COINBASE: "web3_coinbase_wallet_signature"
5206
+ };
5207
+ return clerkUser.createExternalAccount({
5208
+ strategy: strategyMapping[provider],
5209
+ // Cast to any to bypass strict OAuthStrategy check if using Web3
5210
+ redirectUrl: "/account-settings"
5189
5211
  });
5190
5212
  }, "linkAccount"),
5191
- unlinkAccount: /* @__PURE__ */ __name(async (accountId) => {
5192
- return handleAuthAction(async () => store.removeConnectedAccount(accountId));
5213
+ unlinkAccount: /* @__PURE__ */ __name(async (id) => {
5214
+ const account = clerkUser?.externalAccounts.find((a) => a.id === id);
5215
+ return account?.destroy();
5193
5216
  }, "unlinkAccount")
5194
5217
  };
5195
- }, "createAuthContextValue");
5218
+ }, "useClerkAuthClient");
5196
5219
 
5197
5220
  // src/client/hooks/useAuth.ts
5198
- function useAuth() {
5199
- const AuthContext2 = createAuthContextValue();
5200
- return AuthContext2;
5201
- }
5202
- __name(useAuth, "useAuth");
5221
+ var useAuth = /* @__PURE__ */ __name(() => {
5222
+ const adapter = useClerkAuthClient();
5223
+ const { setLoading } = useAuthStore();
5224
+ return {
5225
+ /** Current user object or null if not authenticated */
5226
+ user: adapter.user,
5227
+ /** Boolean indicating if a valid session exists */
5228
+ isAuthenticated: adapter.isAuthenticated,
5229
+ /** Boolean indicating if the auth state is still resolving */
5230
+ isLoading: adapter.isLoading,
5231
+ /**
5232
+ * Initiates OAuth or Web3 Sign In.
5233
+ * Redirects to /dashboard on completion.
5234
+ */
5235
+ signIn: /* @__PURE__ */ __name(async (provider) => {
5236
+ setLoading(true);
5237
+ try {
5238
+ await adapter.signIn(provider);
5239
+ } finally {
5240
+ setLoading(false);
5241
+ }
5242
+ }, "signIn"),
5243
+ /**
5244
+ * Creates a new account.
5245
+ * Redirects to /onboarding on completion.
5246
+ */
5247
+ signUp: /* @__PURE__ */ __name(async (provider) => {
5248
+ setLoading(true);
5249
+ try {
5250
+ await adapter.signUp(provider);
5251
+ } finally {
5252
+ setLoading(false);
5253
+ }
5254
+ }, "signUp"),
5255
+ /** Terminates the current session */
5256
+ signOut: /* @__PURE__ */ __name(async () => {
5257
+ setLoading(true);
5258
+ try {
5259
+ await adapter.signOut();
5260
+ } finally {
5261
+ setLoading(false);
5262
+ }
5263
+ }, "signOut"),
5264
+ /** Links a new social provider to the existing account */
5265
+ linkAccount: /* @__PURE__ */ __name((provider) => adapter.linkAccount(provider), "linkAccount"),
5266
+ /** Removes a linked social provider by its unique account ID */
5267
+ unlinkAccount: /* @__PURE__ */ __name((id) => adapter.unlinkAccount(id), "unlinkAccount")
5268
+ };
5269
+ }, "useAuth");
5203
5270
  var ProtectedRoute = /* @__PURE__ */ __name(({
5204
5271
  children,
5205
5272
  fallback = /* @__PURE__ */ jsxRuntime.jsx("div", { children: "Please sign in to access this page" }),
@@ -5347,18 +5414,92 @@ var useRBAC = /* @__PURE__ */ __name(() => {
5347
5414
  isModerator: hasRole("MODERATOR")
5348
5415
  };
5349
5416
  }, "useRBAC");
5350
-
5351
- // src/client/hooks/useSession.ts
5352
5417
  function useSession() {
5353
- const store = useAuthStore();
5418
+ const { session: clerkSession } = nextjs.useSession();
5419
+ const { user } = nextjs.useUser();
5420
+ const mappedSession = clerkSession && user ? {
5421
+ id: clerkSession.id,
5422
+ userId: user.id,
5423
+ // Grabbed from useUser hook
5424
+ provider: user.publicMetadata?.provider ?? "clerk",
5425
+ // Grabbed from useUser hook
5426
+ providerSessionId: clerkSession.id,
5427
+ expiresAt: clerkSession.expireAt,
5428
+ createdAt: clerkSession.createdAt,
5429
+ lastActivityAt: clerkSession.lastActiveAt,
5430
+ metadata: user.publicMetadata ?? {}
5431
+ } : null;
5354
5432
  return {
5355
- session: store.session,
5356
- isValid: !!store.session,
5357
- expiresAt: store.sessionExpiry,
5358
- refresh: store.refreshTokens
5433
+ session: mappedSession,
5434
+ isValid: !!clerkSession && clerkSession.status === "active",
5435
+ expiresAt: mappedSession?.expiresAt ?? null,
5436
+ refresh: /* @__PURE__ */ __name(async () => {
5437
+ if (clerkSession) {
5438
+ await clerkSession.touch();
5439
+ }
5440
+ }, "refresh")
5359
5441
  };
5360
5442
  }
5361
5443
  __name(useSession, "useSession");
5444
+
5445
+ // src/client/utils/handleAuthAction.ts
5446
+ var handleAuthAction = /* @__PURE__ */ __name(async (action) => {
5447
+ const store = useAuthStore();
5448
+ store.setLoading(true);
5449
+ store.setError(null);
5450
+ try {
5451
+ const result = await action();
5452
+ return result;
5453
+ } catch (err) {
5454
+ const errorMessage = err instanceof Error ? err.message : "Authentication failed";
5455
+ store.setError(errorMessage);
5456
+ throw err;
5457
+ } finally {
5458
+ store.setLoading(false);
5459
+ }
5460
+ }, "handleAuthAction");
5461
+
5462
+ // src/client/utils/createAuthContextValues.ts
5463
+ var createAuthContextValue = /* @__PURE__ */ __name(() => {
5464
+ const store = useAuthStore();
5465
+ return {
5466
+ user: store.user,
5467
+ isAuthenticated: store.isAuthenticated,
5468
+ isLoading: store.isLoading,
5469
+ error: store.error,
5470
+ signIn: /* @__PURE__ */ __name(async (provider, credentials) => {
5471
+ return handleAuthAction(() => store.signIn(provider, credentials));
5472
+ }, "signIn"),
5473
+ signUp: /* @__PURE__ */ __name(async (provider, data) => {
5474
+ return handleAuthAction(() => store.signUp(provider, data));
5475
+ }, "signUp"),
5476
+ signOut: /* @__PURE__ */ __name(async () => {
5477
+ return handleAuthAction(() => store.signOut());
5478
+ }, "signOut"),
5479
+ linkAccount: /* @__PURE__ */ __name(async (userId, provider, data) => {
5480
+ return handleAuthAction(async () => {
5481
+ const connectedAccount = {
5482
+ ...data,
5483
+ userId,
5484
+ provider,
5485
+ providerType: "",
5486
+ providerAccountId: "",
5487
+ isPrimary: false,
5488
+ isVerified: false,
5489
+ isActive: false,
5490
+ linkedAt: /* @__PURE__ */ new Date(),
5491
+ createdAt: /* @__PURE__ */ new Date(),
5492
+ updatedAt: /* @__PURE__ */ new Date()
5493
+ };
5494
+ store.addConnectedAccount(connectedAccount);
5495
+ return connectedAccount;
5496
+ });
5497
+ }, "linkAccount"),
5498
+ unlinkAccount: /* @__PURE__ */ __name(async (accountId) => {
5499
+ return handleAuthAction(async () => store.removeConnectedAccount(accountId));
5500
+ }, "unlinkAccount")
5501
+ };
5502
+ }, "createAuthContextValue");
5362
5503
  var AuthContext = react.createContext(null);
5363
5504
  function AuthProvider({ children }) {
5364
5505
  const authValue = createAuthContextValue();