@duongtrungnguyen/next-helper
Version:
Helper library for Next.js 15
142 lines • 3.75 kB
JavaScript
"use client";
import React, { useState, useEffect } from "react";
import { cookies } from "next/headers";
import { clearAuthCookies, getCurrentUser, refreshAccessToken, setAuthCookies } from "./server";
import { AuthContext } from "./context";
import { libConfig } from "../configs";
import { parseToken } from "../utils";
const AuthProvider = ({ children }) => {
const [state, setState] = useState({
user: null,
isLoading: true,
isAuthenticated: false,
error: null
});
useEffect(() => {
const initAuth = async () => {
try {
const currentUser = await getCurrentUser();
if (currentUser) {
setState({
user: currentUser,
isLoading: false,
isAuthenticated: true,
error: null
});
} else {
setState({
user: null,
isLoading: false,
isAuthenticated: false,
error: null
});
}
} catch (error) {
setState({
user: null,
isLoading: false,
isAuthenticated: false,
error: "Failed to initialize authentication"
});
}
};
initAuth();
}, []);
const login = async (credentials) => {
setState({ ...state, isLoading: true, error: null });
try {
const response = await fetch(
`${libConfig.baseUrl}${libConfig.auth.globalPrefix}${libConfig.auth.endpoints.login}`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(credentials)
}
);
if (response.ok) {
const tokenPair = await response.json();
await setAuthCookies(tokenPair);
setState({
user: await getCurrentUser(),
isLoading: false,
isAuthenticated: true,
error: null
});
} else {
const error = await response.json();
setState({
...state,
isLoading: false,
error: error.message || "Login failed"
});
}
} catch (error) {
setState({
...state,
isLoading: false,
error: "Login request failed"
});
}
};
const logout = async () => {
var _a;
setState({ ...state, isLoading: true });
try {
const cookieStore = await cookies();
const accessToken = (_a = cookieStore.get(libConfig.auth.cookies.accessToken)) == null ? void 0 : _a.value;
await fetch(`${libConfig.baseUrl}${libConfig.auth.globalPrefix}${libConfig.auth.endpoints.logout}`, {
method: "POST",
headers: {
Authorization: parseToken(accessToken)
}
});
} catch (error) {
console.error("Logout error:", error);
} finally {
await clearAuthCookies();
}
setState({
user: null,
isLoading: false,
isAuthenticated: false,
error: null
});
};
const refreshTokens = async () => {
try {
const status = await refreshAccessToken();
if (status) {
return true;
}
setState({
user: null,
isLoading: false,
isAuthenticated: false,
error: null
});
return false;
} catch (error) {
console.error("Token refresh error:", error);
setState({
user: null,
isLoading: false,
isAuthenticated: false,
error: "Failed to refresh authentication"
});
return false;
}
};
const contextValue = {
state,
login,
logout,
refreshTokens
};
return /* @__PURE__ */ React.createElement(AuthContext.Provider, { value: contextValue }, children);
};
export {
AuthProvider
};
//# sourceMappingURL=client-components.js.map