Skip to content

Commit

Permalink
implenment aunthentication function to protect Page components
Browse files Browse the repository at this point in the history
  • Loading branch information
yyaskriloff committed Apr 28, 2024
1 parent c0f0af1 commit 6bb202b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
49 changes: 49 additions & 0 deletions src/handlers/protect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export { default as getKindeServerSession } from '../session/index';
import { redirect } from 'next/navigation'

/**
* A higher-order function that wraps a page component and adds protection logic.
* @param {import('react').ReactNode} page - The page component to be protected.
* @param {Object} config - The configuration options for the protection logic.
* @param {string} config.redirect - The redirect path if the user is not authenticated or does not have the required role or permissions.
* @param {string[]} config.role - The required role(s) for accessing the protected page.
* @param {string|string[]} config.permissions - The required permission(s) for accessing the protected page.
* @param {number} config.statusCode - The status code for the redirect response.
* @returns {Function} - The protected page component.
*/

const protectPage = (page, config = { redirect: '/api/login', statusCode: 302 }) => async (props) => {
const { isAuthenticated, getAccessToken, getPermission } = kinde()
const isSignedIn = await isAuthenticated()

if (!isSignedIn) {
return redirect(config.redirect, { statusCode: 302 })
}

if (config.role) {
const token = await getAccessToken()
const roles = token?.roles
if (!roles || !config.role.some((role) => roles.includes(role))) {
return redirect(config.redirect, { statusCode: 302 })
}
}

if (typeof config.permissions === "string") {
const hasPermission = await getPermission(config.permissions)
if (!hasPermission) {
return redirect(config.redirect, { statusCode: 302 })
}

}

if (Array.isArray(config.permissions)) {
const hasPermission = await Promise.all(config.permissions.map((permission) => getPermission(permission)))
if (!hasPermission.some((permission) => permission)) {
return redirect(config.redirect, { statusCode: 302 })
}
}

return page(props)
}

export default protectPage
3 changes: 2 additions & 1 deletion src/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export {
RegisterLink
} from '../components/index';
export {createKindeManagementAPIClient} from '../api-client';
export {default as handleAuth} from '../handlers/auth';
export { default as handleAuth } from '../handlers/auth';
export { default as protectPage} from '../handlers/protect';

0 comments on commit 6bb202b

Please sign in to comment.