Here today I am gonna use custom hook and create a authorization for admin and other manager roles.
Lets start by creating a custom hook as useUserRole.js
import {useEffect} from 'react'
import { toast } from 'react-toastify'
import {useAuth} from './useAuth'
export const useUserRole = (allowedRoles) => {
const {session} = useAuth()
useEffect(() => {
if (!allowedRoles.includes(session?.user?.role)) {
localStorage.removeItem('session')
window.location.reload()
toast.error(`Unauthorized`)
}
}, [allowedRoles , session])
return true
}
here , we created an custom hook that takes allowedRoles and we are checking the allowedRoles with the role on our session during the login
here the condition is , if the allowedRoles is equal to the role in session then they are allowed to view the provided route else they will be redirect to login page.
Now we can specify the roles.
export const ROLE = {
Admin: 'Admin',
Manager: 'Manager',
User: 'User'
}
Now in any component like Blog.js
import React, { useState } from 'react'
import { useUserRole } from '../../../hooks/useUserRole'
import { ROLE } from '../../../_helpers/Role'
const Blog = () => {
//checking the role
useUserRole([ROLE.Admin]);
return (
<>Blog page</>
)
}
export default Blog
Conclusion
Hence , the authorization is success and hence we can reuse the hook for the protected routes.
Top comments (0)