payload-authjs
Version:
A Payload CMS 3 plugin for Auth.js 5
101 lines (100 loc) • 3.54 kB
JavaScript
"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useCallback, useEffect, useState } from "react";
export const Context = /*#__PURE__*/ createContext({
status: "loading",
session: null,
refresh: ()=>Promise.resolve(null),
refetch: ()=>Promise.resolve(null)
});
/**
* PayloadSessionProvider that provides the session to the context provider
*/ export const PayloadSessionProvider = ({ userCollectionSlug = "users", session = null, children })=>{
const [isLoading, setIsLoading] = useState(!session);
const [localSession, setLocalSession] = useState(session);
/**
* Function to fetch the session
*/ const fetchSession = useCallback(async ({ signal } = {})=>{
/**
* Fetch the session from the server
*
* @see https://payloadcms.com/docs/rest-api/overview#auth-operations
*/ const response = await fetch(`/api/${userCollectionSlug}/me`, {
signal
});
const result = await response.json();
// Set loading to false
setIsLoading(false);
// If the response is ok
if (response.ok && result.user) {
// Update the local session
const localSession = {
user: result.user,
expires: result.exp && typeof result.exp === "number" ? new Date(result.exp * 1000).toISOString() : undefined,
collection: result.collection ?? result.user.collection,
strategy: result.user._strategy ?? result.strategy
};
setLocalSession(localSession);
// Return the session
return localSession;
} else {
// Reset the session
setLocalSession(null);
return null;
}
}, [
userCollectionSlug
]);
/**
* On mount, fetch the session
*/ useEffect(()=>{
const abortController = new AbortController();
void fetchSession({
signal: abortController.signal
});
// Abort the fetch on unmount
return ()=>{
abortController.abort();
};
}, [
fetchSession
]);
/**
* Function to refresh the session
*/ const refresh = async ()=>{
/**
* Refresh the session on the server
*
* @see https://payloadcms.com/docs/rest-api/overview#auth-operations
*/ const response = await fetch(`/api/${userCollectionSlug}/refresh-token`, {
method: "POST"
});
const result = await response.json();
if (response.ok && result.user) {
// Update the local session
const localSession = {
user: result.user,
expires: result.exp && typeof result.exp === "number" ? new Date(result.exp * 1000).toISOString() : undefined,
collection: result.user.collection,
strategy: result.user._strategy ?? result.strategy
};
setLocalSession(localSession);
// Return the session
return localSession;
} else {
// Reset the session
setLocalSession(null);
return null;
}
};
return /*#__PURE__*/ _jsx(Context, {
value: {
status: isLoading ? "loading" : localSession ? "authenticated" : "unauthenticated",
session: localSession,
refresh,
refetch: fetchSession
},
children: children
});
};
//# sourceMappingURL=PayloadSessionProvider.js.map