Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    LinkedIn

    Optimizing LinkedIn Lead Generation: Seamless CRM Integration

    Node.js

    Nodejs Lesson 15: Internals of Nodejs: LibUV

    Soshace

    Soshace became a media partner of Running Remote Conference 2020

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Monday, September 29
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / POS Tutorial / Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC
    Node.js

    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

    Krissanawat KaewsanmuangBy Krissanawat KaewsanmuangSeptember 30, 2020Updated:March 9, 2021No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC
    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC
    Create simple POS with React.js, Node.js, and MongoDB #15: Simple RBAC

    Defenition: POS – “Point of Sale”. At the point of sale, the merchant calculates the amount owed by the customer, indicates that amount, may prepare an invoice for the customer (which may be a cash register printout), and indicates the options for the customer to make payment.

    In the previous chapters, we integrate the React table with the react-table package and added more dynamic features to it which made the Table. In this chapter, we are going to continue from where we left off from the previous chapter intuitive with a plethora of functionalities.

    In this chapter, we are going to continue from where we left off from the previous chapter. We are going to work on Role-Based Access Control (RBAC) feature for our react app. We are going to have two roles for now: admin and employee.

    1. Admin can control everything in the app.
    2. Employees can only view specific screens and perform specific functions.

    The implementation of the employee role is simple as we already have fields that specify user roles. We are going to use those user roles for conditional rendering with the react-rbac-guard package. This package solves our problem easily and makes things easier while conditional rendering. The sole purpose of this package is to manage the visibility of particular components depending on user credentials.

    We are going to work on the frontend section of the project for this chatter.

    So, let’s get started!

    Installing RBAC package

    First, we need to install the react-rbac package by running the following command in our project terminal:

    yarn add react-rbac-guard

    Fortunately, they provide a demo as well which helps a lot to implement in our project.

    Read More:  React Lesson 5: React Devtools and Reusable Open-Source Components

    Defining Roles

    Now, we are going to define the two roles as mentioned above. It is going to be an array named Roles with object defining role name and credentials as displayed in the code snippet below:

    File: src/constants/index.js
    
    export const Roles = [
      { name: "Admin", credentials: "admin" },
      { name: "Staff", credentials: "staff" },
    ]

    Here, we have defined the role array in the index.js file.

    Next, we need to copy the sample code from the demo that handles RBAC and paste it on the components folder as directed in the folder structure screenshot below:

    React RBAC guard demo
    React RBAC guard demo

    Now, we need to create a create Requirement.js file in the component folder and we import Requirement class from the demo folder that we copied before. Then, we use the Requirement module in order to compare roles that use to decide whether to render the component for users or not. Here, we have created and exported two conditional objects NeedAdmin and NeedStaff for handling the conditional rendering as shown in the code snippet below:

    import { Requirement } from "./react-guard/src";
    
    class MyRequirement extends Requirement {
        constructor(credentials) {
            super();
            this.credentials = credentials;
        }
    isSatisfied(credentials) {
            return this.credentials === credentials;
        }
    }
    const NeedAdmin = new MyRequirement("admin");
    const NeedStaff = new MyRequirement("staff");
    export { NeedAdmin, NeedStaff };

    next, we gonna use on sidebar open sidebar component and we start with import three files that we create to this

    import {
      CredentialProvider,
      Guard,
      any,
      not,
      guardFactory,
      protect
    } from "../react-guard/src";
    import { NeedAdmin, NeedStaff } from "../requirements";
    import { Roles } from '../../constants/'

    Next, we need to define the state called role and object for handling the renders using the useState hook from react and guardFactory functional module from the RBAC package as shown in the code snippet below:

      const [role, setRole] = useState([])
      const Admin = guardFactory(NeedAdmin);
      const Staff = guardFactory(NeedStaff);

    Then, we need to grab the role data from local storage and compare it with the Role objects that we imported. After that, we need to assign the compared value outcome to the role state as shown in the code snippet below:

    const getcurrentRole = () => {
        let token = localStorage.getItem("token");
        var base64Url = token.split(".")[1];
        var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
        var jsonPayload = decodeURIComponent(
          atob(base64)
            .split("")
            .map(function (c) {
              return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
            })
            .join("")
        );
        let { level } = JSON.parse(jsonPayload);
        let currentRole = Roles.find(e => e.credentials === level)
        setRole(currentRole)
      }

    We also need to trigger the compare function getcurrentRole every time the component loads. Hence, we are going to call the function inside the useEffect hook as directed in the code snippet below:

    useEffect(() => {
        getcurrentRole()
      }, [])

    Using conditional rendering is simple and easy. Now, we just need to wrap the view with context class and pass the role. Here, we wrap the CreentialProvider component with value prop of role credential inside which we have wrapped the sections that we want to show to admin using the Admin component. The implementation can be seen in the code snippet below:

    <CredentialProvider value={role.credentials}>
                    <Admin>
                    <li className="nav-item">
                      <Link to="/posmachine" className="nav-link">
                        <i className="nav-icon fas fa-th" />
                        <p>Pos Machine</p>
                      </Link>
                    </li>
                  </Admin>
                  <Admin>
                    <li className="nav-item">
                      <Link to="/branch" className="nav-link">
                        <i className="nav-icon fas fa-building" />
                        <p>Branch</p>
                      </Link>
                    </li>
                  </Admin>
    </CredentialProvider>

    And finally, in order to show that it works on different user roles, we update the header to show the user role. For that, we need to go to the Header component and extract user data from the token that is being stored store on local storage as directed in the code snippet below:

    const [role, setRole] = useState("")
      const [username, setUsername] = useState("")
      useEffect(() => {
        getcurrentRole()
      }, [])
      const getcurrentRole = () => {
        let token = localStorage.getItem("token");
        var base64Url = token.split(".")[1];
        var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
        var jsonPayload = decodeURIComponent(
          atob(base64)
            .split("")
            .map(function (c) {
              return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
            })
            .join("")
        );
       let { level, username } = JSON.parse(jsonPayload);
        setUsername(username)
        setRole(level)
    }

    Then, we attach the role in the menu dropdown for the user as displayed in the code snippet below:

    <li className="nav-item dropdown">
              <a className="nav-link" data-toggle="dropdown" href="#">
                <i className="far fa-user" /> Hello,{role} {username}
              </a>

    Now, whenever we log in to the app, we will see the role and username as displayed in the screenshot below:

    React POS display user name
    React POS display user name

    Now it is time for testing to see if the conditional rendering works for staff as well. The testing process is displayed in the following screenshot demo:

    React POS RBAC result
    React POS RBAC result

    Here, we can see that whenever we log in as staff or an employee, we only get three menu options on the left sidebar. This proves that our implementation works.

    The work here was simple and easy to understand. We successfully implemented the role-based access control using the objects and modules from the react-rbac-guard package.

    Your challenge…

    Now for the next step, you can implement this role-based access control for the staff. You can use it to render out the portions that you don’t want your staff to access. Make sure to clone this app and study the codes. I am eagerly waiting to review your work

    Conclusion

    This tutorial has been long and interesting. But it does not end here. We implemented lots of functionality in our POS system. In previous chapters, we dealt with functionalities of the React table and made it efficient, dynamic, and full-fledged. This chapter was something new. We got detailed guidance on how to make use of components and modules from the react-rbac-guard package to implement the role-based access control for the admin and staff roles. The method was made pretty easy by the package with a great concept to grab as well.

    In our next chapter, we will continue our work on an important section that is the drawer screen which we are going to use for calculating sales and orders.

    The coding implementations used in this tutorial chapter are available on Github.

    See you in the next chapter! Peace out!

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Krissanawat Kaewsanmuang
    • Website
    • X (Twitter)

    Developer Relation @instamobile.io

    Related Posts

    An Introduction to Clustering in Node.js

    March 26, 2024

    JAMstack Architecture with Next.js

    March 15, 2024

    Rendering Patterns: Static and Dynamic Rendering in Nextjs

    March 7, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Interview December 23, 2019

    Ultimate List of JavaScript Interview Questions

    More than 90 questions for Juniors, Middle and Senior Developers. Both practical and theoretical.

    18. Уроки Node.js. Работа с Файлами, Модуль fs

    October 18, 2016

    Elevate the UX+DX+EX with Gatsby & Agility CMS

    June 17, 2020

    Svelte for React Developers

    December 17, 2020

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Уроки React. Урок 13. Часть 2.

    Programming November 10, 2016

    True Freelancer’s story

    Comics November 15, 2016

    Implementing Machine Learning in Web Applications with Python and TensorFlow

    Flask April 7, 2023

    Conducting a Better Technical Interview: Problems and Solutions

    Interview March 13, 2019

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    SEO & Analytics

    Strategies to Mitigate Duplicate Content in Programmatic SEO

    Beginners

    Getting Started with React Native in 2020

    Tips

    A Few Productivity Tips and Tools for Web Developers

    Most Popular

    Maximizing Lead Generation with LinkedIn InMail Strategies

    LinkedIn

    Ultimate List of JavaScript Interview Questions

    Interview

    The Ultimate Introduction to Kafka with JavaScript

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.