Tommy Leong
Tommy Leong

Reputation: 3030

Elegant way of handling what to show based on authorization

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
}

Upvotes: 0

Views: 94

Answers (2)

Sadek Mehri
Sadek Mehri

Reputation: 70

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>}
    </>
  )
}

Upvotes: 0

Ahmed Sbai
Ahmed Sbai

Reputation: 16249

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

Upvotes: 0

Related Questions