Elegant way of handling what to show based on authorization

68 Views Asked by At

Within the application, we are thinking to hide/show certain button actions based on user authorization. This authorization is a payload that read from DB upon user logged in, instead part of cookie.

Im hoping to find a way of handling such control in a more cleaner manner instead of doing IF ELSE statement to the related page/component.

Question:

What could be an elegant way to handle such control?

Current idea in mind:

##Solution1:
1. Upon logged in, update Redux with the payload given.
2. Read the Redux value on pages that has such control. 

if(user.role===admin){
    ..continueToShowButton
}else{
    ..hideTheButtonFromComponent / ..hideTheButtonFromPage
}

2

There are 2 best solutions below

2
Ahmed Sbai On

Inside your JSX you can do this:

<>
 {user.role === admin && <button>Admin button</button> }
</>

this will show the button only if the condition is met.


using nextjs I recommand Next-auth for user authentication, you can create a session where you store information for each user logged then based on its role that you get from your backend you decide either to show or hide the button you don't need Redux for this

0
Sadek Mehri On
const ROLES = {
  ADMIN: 'admin',
  USER: 'user',
  GUEST: 'guest'
};

const hasRole = (user, role) => user.role === role

const MyComponent = () => {
  const user = getUser() // Assuming you have a function to get the user object
  const isUserInvalid = !user || !user.role
   
  if (isUserInvalid) return null
  
  return (
    <>
      {hasRole(user, ROLES.ADMIN) && <button>Admin Button</button>}
      {hasRole(user, ROLES.USER) && <button>User Button</button>}
      {hasRole(user, ROLES.GUEST) && <button>Guest Button</button>}
    </>
  )
}