Using Routers for web authentication

Here is my task I want to solve:

-User logs in to their profile (using just Wix’s login system)
-They attempt to access a staff page (All staff members are users on the website, but not all users are staff members)
-If they are staff members, they can access the page

  • If not, they can’t access it

Now I’ve already “solved” the problem using a simple redirect. I query the database that checks their email against an email of all staff members. It works decently, but if you type in the address, you see the page momentarily even if you’re not logged in.

I was told I could use routers, but honestly I don’t know a ton about routers. Also, all the tutorials seem to be for building dynamic pages. Most of these staff pages are not dynamic, but are static. Any help? The attempt I have to start working with routers, I’m getting “cannot access backend” errors.

This is a good question and I haven’t seen much in these forums or online, examples-wise, covering it.

My read on it is that you need to do something like the following:

  1. Think about which of your site pages are public, and which are private or authenticated. (This can be broken down again into: which are visible by non-staff users, and which are only visible to staff users.)
  2. For all the private/authenticated pages, namespace their URLs such that they site behind your auth router. For example, if you have a “Staff Only” private page, its URL path should be /staff/some-page and your router should look akin to:
function staff_Router(request) {
  const path = request.path[0]
  if (path === 'some-page') {
    // make sure the 
    if (request.user && request.user.role == 'Admin') {
      return next()
    } else {
      return redirect('/another-resource', 301)
    }
  }
}

Of course you’ll need to add all your staff-only resources in here and make sure all those pages are prefixed with the /staff namespace, but that I think is the general idea.

@StevenCrowley has been working on a user-auth router so can probably weigh in as well.