@thetechfossil/auth2 1.2.2 → 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.
@@ -1,9 +1,7 @@
1
+ "use client";
1
2
  import axios from 'axios';
2
3
  import { createContext, useState, useCallback, useEffect, useContext, useRef } from 'react';
3
4
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
- import { cookies } from 'next/headers';
5
- import { redirect } from 'next/navigation';
6
- import { NextResponse } from 'next/server';
7
5
 
8
6
  // src/core/http-client.ts
9
7
  var HttpClient = class {
@@ -400,21 +398,21 @@ var AuthService = class {
400
398
  if (!this.token) {
401
399
  throw new Error("Not authenticated");
402
400
  }
403
- const response = await this.httpClient.get("/api/v1/session");
401
+ const response = await this.httpClient.get("/api/v1/sessions");
404
402
  return response;
405
403
  }
406
404
  async revokeSession(sessionId) {
407
405
  if (!this.token) {
408
406
  throw new Error("Not authenticated");
409
407
  }
410
- const response = await this.httpClient.delete(`/api/v1/session/${sessionId}`);
408
+ const response = await this.httpClient.delete(`/api/v1/sessions/${sessionId}`);
411
409
  return response;
412
410
  }
413
411
  async revokeAllSessions() {
414
412
  if (!this.token) {
415
413
  throw new Error("Not authenticated");
416
414
  }
417
- const response = await this.httpClient.delete("/api/v1/session/revoke/all");
415
+ const response = await this.httpClient.delete("/api/v1/sessions/revoke/all");
418
416
  this.token = null;
419
417
  this.httpClient.removeAuthToken();
420
418
  this.removeTokenFromStorage();
@@ -469,8 +467,8 @@ var useAuth = (config) => {
469
467
  const authenticated = authService.isAuthenticated();
470
468
  setIsAuthenticated(authenticated);
471
469
  if (authenticated) {
472
- const currentUser2 = authService.getCurrentUser();
473
- setUser(currentUser2);
470
+ const currentUser = authService.getCurrentUser();
471
+ setUser(currentUser);
474
472
  } else {
475
473
  setUser(null);
476
474
  }
@@ -605,8 +603,8 @@ var AuthProvider = ({ children, config }) => {
605
603
  const authenticated = authService.isAuthenticated();
606
604
  if (authenticated) {
607
605
  try {
608
- const currentUser2 = authService.getCurrentUser();
609
- setUser(currentUser2);
606
+ const currentUser = authService.getCurrentUser();
607
+ setUser(currentUser);
610
608
  } catch (error) {
611
609
  console.error("Failed to get current user:", error);
612
610
  setUser(null);
@@ -2189,9 +2187,9 @@ var SignIn = ({ redirectUrl, appearance }) => {
2189
2187
  const [success, setSuccess] = useState(null);
2190
2188
  useEffect(() => {
2191
2189
  if (isSignedIn && redirectUrl) {
2192
- const redirect2 = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGIN || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGIN || "/dashboard";
2190
+ const redirect = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGIN || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGIN || "/dashboard";
2193
2191
  const baseUrl = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL || (typeof window !== "undefined" ? window.location.origin : "");
2194
- window.location.href = `${baseUrl}${redirect2}`;
2192
+ window.location.href = `${baseUrl}${redirect}`;
2195
2193
  }
2196
2194
  }, [isSignedIn, redirectUrl]);
2197
2195
  const handleSubmit = async (e) => {
@@ -2460,9 +2458,9 @@ var SignUp = ({ redirectUrl, appearance }) => {
2460
2458
  const [success, setSuccess] = useState(null);
2461
2459
  useEffect(() => {
2462
2460
  if (isSignedIn && redirectUrl) {
2463
- const redirect2 = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_REGISTER || process.env.REACT_APP_AUTH_REDIRECT_AFTER_REGISTER || "/dashboard";
2461
+ const redirect = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_REGISTER || process.env.REACT_APP_AUTH_REDIRECT_AFTER_REGISTER || "/dashboard";
2464
2462
  const baseUrl = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL || (typeof window !== "undefined" ? window.location.origin : "");
2465
- window.location.href = `${baseUrl}${redirect2}`;
2463
+ window.location.href = `${baseUrl}${redirect}`;
2466
2464
  }
2467
2465
  }, [isSignedIn, redirectUrl]);
2468
2466
  const getPasswordStrength = (pwd) => {
@@ -2739,9 +2737,9 @@ var SignOut = ({ redirectUrl }) => {
2739
2737
  useEffect(() => {
2740
2738
  const performSignOut = async () => {
2741
2739
  await signOut();
2742
- const redirect2 = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGOUT || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGOUT || "/";
2740
+ const redirect = redirectUrl || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGOUT || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGOUT || "/";
2743
2741
  const baseUrl = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL || (typeof window !== "undefined" ? window.location.origin : "");
2744
- window.location.href = `${baseUrl}${redirect2}`;
2742
+ window.location.href = `${baseUrl}${redirect}`;
2745
2743
  };
2746
2744
  performSignOut();
2747
2745
  }, [signOut, redirectUrl]);
@@ -2767,9 +2765,9 @@ var UserButton = ({ showName = false, appearance }) => {
2767
2765
  };
2768
2766
  const handleSignOut = async () => {
2769
2767
  await signOut();
2770
- const redirect2 = process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGOUT || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGOUT || "/";
2768
+ const redirect = process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGOUT || process.env.REACT_APP_AUTH_REDIRECT_AFTER_LOGOUT || "/";
2771
2769
  const baseUrl = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL || (typeof window !== "undefined" ? window.location.origin : "");
2772
- window.location.href = `${baseUrl}${redirect2}`;
2770
+ window.location.href = `${baseUrl}${redirect}`;
2773
2771
  };
2774
2772
  return /* @__PURE__ */ jsxs("div", { style: { position: "relative", ...appearance?.elements?.userButtonBox }, ref: dropdownRef, children: [
2775
2773
  /* @__PURE__ */ jsxs(
@@ -2962,9 +2960,9 @@ var VerifyEmail = ({ token, onSuccess, onError }) => {
2962
2960
  setMessage("Email verified successfully! Redirecting...");
2963
2961
  onSuccess?.();
2964
2962
  setTimeout(() => {
2965
- const redirect2 = process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_VERIFY || process.env.REACT_APP_AUTH_REDIRECT_AFTER_VERIFY || "/dashboard";
2963
+ const redirect = process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_VERIFY || process.env.REACT_APP_AUTH_REDIRECT_AFTER_VERIFY || "/dashboard";
2966
2964
  const baseUrl = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL || (typeof window !== "undefined" ? window.location.origin : "");
2967
- window.location.href = `${baseUrl}${redirect2}`;
2965
+ window.location.href = `${baseUrl}${redirect}`;
2968
2966
  }, 2e3);
2969
2967
  } else {
2970
2968
  setStatus("error");
@@ -4004,8 +4002,8 @@ var useNextAuth = (config) => {
4004
4002
  const authenticated = authService.isAuthenticated();
4005
4003
  setIsAuthenticated(authenticated);
4006
4004
  if (authenticated) {
4007
- const currentUser2 = authService.getCurrentUser();
4008
- setUser(currentUser2);
4005
+ const currentUser = authService.getCurrentUser();
4006
+ setUser(currentUser);
4009
4007
  } else {
4010
4008
  setUser(null);
4011
4009
  }
@@ -4163,276 +4161,6 @@ var useNextAuth = (config) => {
4163
4161
  };
4164
4162
  };
4165
4163
 
4166
- // src/node/auth-client.ts
4167
- var AuthClient = class extends AuthService {
4168
- constructor(config) {
4169
- super(config);
4170
- }
4171
- // Override methods that require browser-specific features
4172
- // For Node.js, token persistence must be handled manually
4173
- async register(data) {
4174
- const frontendBaseUrl = process.env.FRONTEND_BASE_URL || process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || process.env.REACT_APP_FRONTEND_BASE_URL;
4175
- if (frontendBaseUrl) {
4176
- this["httpClient"].setFrontendBaseUrl(frontendBaseUrl);
4177
- }
4178
- const response = await this["httpClient"].post("/api/v1/auth/register", data);
4179
- if (response.success && response.message === "Registration data saved. Verification email sent. Please check your inbox.") {
4180
- return response;
4181
- }
4182
- throw new Error(response.message || "Registration failed");
4183
- }
4184
- async login(data) {
4185
- const response = await this["httpClient"].post("/api/v1/auth/login", data);
4186
- if (response.success && response.token) {
4187
- this["token"] = response.token;
4188
- this["httpClient"].setAuthToken(response.token);
4189
- return response;
4190
- }
4191
- if (response.success && response.message === "OTP sent to your email.") {
4192
- return response;
4193
- }
4194
- if (response.success && response.message === "OTP verified successfully." && response.token) {
4195
- this["token"] = response.token;
4196
- this["httpClient"].setAuthToken(response.token);
4197
- return response;
4198
- }
4199
- throw new Error(response.message || "Login failed");
4200
- }
4201
- async verify(data) {
4202
- const response = await this["httpClient"].post("/api/v1/auth/verify", data);
4203
- if (response.success && response.token) {
4204
- this["token"] = response.token;
4205
- this["httpClient"].setAuthToken(response.token);
4206
- }
4207
- return response;
4208
- }
4209
- async logout() {
4210
- this["token"] = null;
4211
- this["httpClient"].removeAuthToken();
4212
- }
4213
- async getProfile() {
4214
- if (!this["token"]) {
4215
- throw new Error("Not authenticated");
4216
- }
4217
- const response = await this["httpClient"].get("/api/v1/user/me");
4218
- return response.user;
4219
- }
4220
- async getUserById(id) {
4221
- const response = await this["httpClient"].get(`/api/v1/user/${id}`);
4222
- return response.user;
4223
- }
4224
- async updateProfile(data) {
4225
- if (!this["token"]) {
4226
- throw new Error("Not authenticated");
4227
- }
4228
- const response = await this["httpClient"].post("/api/v1/user/update/name", data);
4229
- if (response.success && response.token) {
4230
- this["token"] = response.token;
4231
- this["httpClient"].setAuthToken(response.token);
4232
- }
4233
- return response;
4234
- }
4235
- async getAllUsers() {
4236
- if (!this["token"]) {
4237
- throw new Error("Not authenticated");
4238
- }
4239
- const response = await this["httpClient"].get("/api/v1/user/all");
4240
- return response.users;
4241
- }
4242
- };
4243
-
4244
- // src/nextjs/server-auth.ts
4245
- var NextServerAuth = class extends AuthClient {
4246
- constructor(config) {
4247
- super(config);
4248
- }
4249
- // Parse token from request headers
4250
- static parseTokenFromHeaders(headers) {
4251
- const authHeader = headers.get("authorization");
4252
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
4253
- return null;
4254
- }
4255
- return authHeader.substring(7);
4256
- }
4257
- // Parse token from cookies
4258
- static parseTokenFromCookies(cookies2) {
4259
- const cookieArray = cookies2.split(";");
4260
- for (const cookie of cookieArray) {
4261
- const [name, value] = cookie.trim().split("=");
4262
- if (name === "auth_token") {
4263
- return decodeURIComponent(value);
4264
- }
4265
- }
4266
- return null;
4267
- }
4268
- // Parse token from Next.js request object
4269
- static parseTokenFromRequest(req) {
4270
- if (req.headers) {
4271
- const authHeader = req.headers.authorization || req.headers.Authorization;
4272
- if (authHeader && authHeader.startsWith("Bearer ")) {
4273
- return authHeader.substring(7);
4274
- }
4275
- }
4276
- if (req.cookies) {
4277
- return req.cookies.auth_token || null;
4278
- }
4279
- if (req.headers && req.headers.cookie) {
4280
- return this.parseTokenFromCookies(req.headers.cookie);
4281
- }
4282
- return null;
4283
- }
4284
- // Verify token and get user
4285
- async verifyToken(token) {
4286
- try {
4287
- this["httpClient"].setAuthToken(token);
4288
- const user = await this.getProfile();
4289
- return user;
4290
- } catch (error) {
4291
- console.error("Token verification failed:", error);
4292
- return null;
4293
- }
4294
- }
4295
- // Create authenticated client with token
4296
- static createAuthenticatedClient(config, token) {
4297
- const client = new NextServerAuth(config);
4298
- client["httpClient"].setAuthToken(token);
4299
- client["token"] = token;
4300
- return client;
4301
- }
4302
- };
4303
- var AuthServer = class {
4304
- constructor(config) {
4305
- this.config = {
4306
- authApiUrl: config?.authApiUrl || process.env.AUTH_API_URL || "http://localhost:7000",
4307
- tokenCookieName: config?.tokenCookieName || "auth_token"
4308
- };
4309
- }
4310
- async getToken() {
4311
- const cookieStore = await cookies();
4312
- const token = cookieStore.get(this.config.tokenCookieName);
4313
- return token?.value || null;
4314
- }
4315
- async getCurrentUser() {
4316
- const token = await this.getToken();
4317
- if (!token)
4318
- return null;
4319
- try {
4320
- const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
4321
- return payload.user || null;
4322
- } catch (error) {
4323
- console.error("Failed to parse user from token:", error);
4324
- return null;
4325
- }
4326
- }
4327
- async isAuthenticated() {
4328
- const token = await this.getToken();
4329
- return !!token;
4330
- }
4331
- async requireAuth(redirectTo) {
4332
- const user = await this.getCurrentUser();
4333
- if (!user) {
4334
- const loginPath = redirectTo || process.env.NEXT_PUBLIC_AUTH_REDIRECT_TO_LOGIN || "/auth/login";
4335
- redirect(loginPath);
4336
- }
4337
- return user;
4338
- }
4339
- async redirectIfAuthenticated(redirectTo) {
4340
- const isAuth = await this.isAuthenticated();
4341
- if (isAuth) {
4342
- const dashboardPath = redirectTo || process.env.NEXT_PUBLIC_AUTH_REDIRECT_AFTER_LOGIN || "/dashboard";
4343
- redirect(dashboardPath);
4344
- }
4345
- }
4346
- async getProfile() {
4347
- const token = await this.getToken();
4348
- if (!token)
4349
- return null;
4350
- try {
4351
- const response = await fetch(`${this.config.authApiUrl}/api/v1/user/me`, {
4352
- headers: {
4353
- "Authorization": `Bearer ${token}`
4354
- }
4355
- });
4356
- if (!response.ok) {
4357
- return null;
4358
- }
4359
- const data = await response.json();
4360
- return data.user;
4361
- } catch (error) {
4362
- console.error("Failed to fetch profile:", error);
4363
- return null;
4364
- }
4365
- }
4366
- };
4367
- var authServerInstance = null;
4368
- function getAuthServer(config) {
4369
- if (!authServerInstance) {
4370
- authServerInstance = new AuthServer(config);
4371
- }
4372
- return authServerInstance;
4373
- }
4374
- async function currentUser() {
4375
- const auth2 = getAuthServer();
4376
- return auth2.getCurrentUser();
4377
- }
4378
- async function auth() {
4379
- const authServer = getAuthServer();
4380
- const user = await authServer.getCurrentUser();
4381
- const token = await authServer.getToken();
4382
- return {
4383
- user,
4384
- userId: user?._id || null,
4385
- isAuthenticated: !!user,
4386
- token
4387
- };
4388
- }
4389
- async function requireAuth(redirectTo) {
4390
- const authServer = getAuthServer();
4391
- return authServer.requireAuth(redirectTo);
4392
- }
4393
- async function redirectIfAuthenticated(redirectTo) {
4394
- const authServer = getAuthServer();
4395
- return authServer.redirectIfAuthenticated(redirectTo);
4396
- }
4397
- function authMiddleware(config) {
4398
- const {
4399
- publicRoutes = ["/auth/login", "/auth/register", "/auth/verify-email", "/auth/forgot-password", "/auth/reset-password"],
4400
- protectedRoutes = ["/dashboard"],
4401
- loginUrl = "/auth/login",
4402
- afterLoginUrl = "/dashboard",
4403
- tokenCookieName = "auth_token"
4404
- } = config || {};
4405
- return function middleware(request) {
4406
- const { pathname } = request.nextUrl;
4407
- const token = request.cookies.get(tokenCookieName)?.value;
4408
- const isAuthenticated = !!token;
4409
- const isPublicRoute = publicRoutes.some((route) => {
4410
- if (route.endsWith("*")) {
4411
- return pathname.startsWith(route.slice(0, -1));
4412
- }
4413
- return pathname === route || pathname.startsWith(route + "/");
4414
- });
4415
- const isProtectedRoute = protectedRoutes.some((route) => {
4416
- if (route.endsWith("*")) {
4417
- return pathname.startsWith(route.slice(0, -1));
4418
- }
4419
- return pathname === route || pathname.startsWith(route + "/");
4420
- });
4421
- if (isAuthenticated && isPublicRoute) {
4422
- return NextResponse.redirect(new URL(afterLoginUrl, request.url));
4423
- }
4424
- if (!isAuthenticated && isProtectedRoute) {
4425
- const loginUrlWithRedirect = new URL(loginUrl, request.url);
4426
- loginUrlWithRedirect.searchParams.set("redirect", pathname);
4427
- return NextResponse.redirect(loginUrlWithRedirect);
4428
- }
4429
- return NextResponse.next();
4430
- };
4431
- }
4432
- function createAuthMiddleware(config) {
4433
- return authMiddleware(config);
4434
- }
4435
-
4436
- export { AuthFlow, AuthProvider, AuthServer, AuthService, ChangePassword, EmailVerificationPage, ForgotPassword, HttpClient, LoginForm, NextServerAuth, OtpForm, ProtectedRoute, PublicRoute, RegisterForm, ResetPassword, SignIn, SignOut, SignUp, UserButton, UserProfile, VerifyEmail, auth, authMiddleware, createAuthMiddleware, currentUser, getAuthServer, redirectIfAuthenticated, requireAuth, useAuth2 as useAuth, useAuth as useAuthLegacy, useNextAuth };
4164
+ export { AuthFlow, AuthProvider, AuthService, ChangePassword, EmailVerificationPage, ForgotPassword, HttpClient, LoginForm, OtpForm, ProtectedRoute, PublicRoute, RegisterForm, ResetPassword, SignIn, SignOut, SignUp, UserButton, UserProfile, VerifyEmail, useAuth2 as useAuth, useAuth as useAuthLegacy, useNextAuth };
4437
4165
  //# sourceMappingURL=out.js.map
4438
4166
  //# sourceMappingURL=index.next.mjs.map