Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Performance Optimizations for React Native Applications

    Lead Generation

    The Ultimate Guide to Local Lead Generation for Home Service Providers

    Job

    3 Proven Strategies to Find Work-Life Balance for Remote Workers

    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
    Saturday, September 6
    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:  Building a Full Stack Application using RedwoodJS

    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
    JavaScript October 14, 2020

    Create simple POS with React.js, Node.js, and MongoDB #16: Order Screen

    In this chapter, we are going to create an order page. The order page displays the products and the calculator to help calculate the total price. Finally, we will save the transaction to the database.

    Think Like a Pythonista — Building a Book Sharing App

    February 6, 2020

    Strategies for Developing High-Performing Project Teams

    December 7, 2024

    Работа с заказчиком

    December 31, 2015

    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

    Ways to optimize React applications

    JavaScript July 24, 2020

    Responsible Web Scraping: Gathering Data Ethically and Legally

    JavaScript September 11, 2019

    Essential Steps to Identify and Validate Your Business Ideas

    Entrepreneurship November 30, 2024

    Programming Patterns. Publisher/Subscriber, Mediator

    Programming March 7, 2017

    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
    Programming

    13. Уроки Node.js. Разработка, supervisor

    Node.js

    Node.js Lesson 5: Global modules

    JavaScript

    Strategies for Developing High-Performing Project Teams

    Most Popular

    Outdated MVP

    Comics

    Short React Story

    Programming

    Node.js Experience

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

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