@pubflow/nextjs
Version:
Next.js adapter for Pubflow framework
57 lines (56 loc) • 2.1 kB
JavaScript
/**
* Server Authentication Hook for Next.js
*
* Provides a hook for handling authentication with automatic redirects
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.useServerAuth = useServerAuth;
const react_1 = require("react");
const router_1 = require("next/router");
const useAuth_1 = require("./useAuth");
/**
* Hook for handling authentication with automatic redirects
*
* @param options Hook options
* @returns Authentication hook result
*/
function useServerAuth({ loginRedirectPath = '/login', allowedTypes = ['authenticated'], validateOnMount = true, instanceId } = {}) {
const { user, isAuthenticated, isLoading, validateSession } = (0, useAuth_1.useAuth)(instanceId);
const router = (0, router_1.useRouter)();
(0, react_1.useEffect)(() => {
// Validate session on mount if configured
if (validateOnMount) {
validateSession().then(({ isValid }) => {
if (!isValid) {
router.push(`${loginRedirectPath}?redirect=${encodeURIComponent(router.asPath)}`);
}
});
}
}, [validateOnMount, loginRedirectPath, router, validateSession]);
(0, react_1.useEffect)(() => {
// Skip if still loading
if (isLoading) {
return;
}
// Redirect if not authenticated
if (!isAuthenticated) {
router.push(`${loginRedirectPath}?redirect=${encodeURIComponent(router.asPath)}`);
return;
}
// Check user type if allowedTypes doesn't include 'authenticated'
if (!allowedTypes.includes('authenticated') && user) {
const userType = user.userType || '';
const isAllowed = allowedTypes.some(type => type.toLowerCase() === userType.toLowerCase());
if (!isAllowed) {
router.push('/access-denied');
}
}
}, [isLoading, isAuthenticated, user, allowedTypes, loginRedirectPath, router]);
return {
user,
isAuthenticated,
isLoading,
validateSession
};
}
;