-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dde8e13
commit 7bc0bc3
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import React, { useEffect, useState } from "react"; | ||
import { useRouter } from "next/navigation"; | ||
import { useAppSelector } from "@/core/redux/hooks"; | ||
import type { RootState } from "@/core/redux/store"; | ||
|
||
const withPermission = <P extends object>( | ||
Component: React.ComponentType<P>, | ||
requiredPermission: string | ||
): React.FC<P> => { | ||
const WithPermission: React.FC<P> = (props) => { | ||
const router = useRouter(); | ||
const currentRole = useAppSelector( | ||
(state: RootState) => state.user.currentRole | ||
); | ||
const [hasPermission, setHasPermission] = useState(false); | ||
|
||
useEffect(() => { | ||
if (currentRole) { | ||
const permissionExists = currentRole.permissions.includes( | ||
requiredPermission | ||
); | ||
setHasPermission(permissionExists); | ||
|
||
if (!permissionExists) { | ||
router.push("/permission-denied"); | ||
} | ||
} | ||
}, [currentRole, requiredPermission, router]); | ||
|
||
if (!hasPermission) return null; | ||
|
||
return <Component {...props} />; | ||
}; | ||
|
||
return WithPermission; | ||
}; | ||
|
||
export default withPermission; |