Redirecting to another page based on field

Hi folks, I’ve built myself a very dodgy home grown email-based MFA, which I do have working, but one of the things I’ve had to do to make it work is to set a RULE on every page to redirect to the HOME page if a field in the Accounts table called STATUS is not set to “AUTH” for the logged in user.

I’m hoping to avoid having to set up that rule everywhere (because I have lots of pages) by using javascript to do it as a global thing (with a couple of pages being exceptions), but I’m not much of a coder.

Could someone who is a good coder please do me a big favour and provide a snippet of code that effectively says "on rendering any scene except scene_XX, scene_YY, scene_ZZ, redirect to #HOME if object_1 field_76 <> “AUTH”.

Once I have this working, I’ll write up what I’ve done and maybe some others can get some value from it, until Knack finally set up a real MFA solution for app users.

This is the page rule I’m hoping to replace:

Hi @LeighBerre96926,

See below.

(Note: Since your object is an Account, I used Knack.getUserAttributes().values to access fields in the Accounts table.)

Hope this helps.

$(document).on('knack-scene-render.any', function (event, scene) {
  const loginStateFieldKey = 'field_76' // Modify as needed
  const scenesToExclude = ['scene_1', 'scene_2'] // Modify as needed
  const redirectPage = 'home' // Modify as needed
  const authValue = 'AUTH' // Modify as needed
  const currentPage = Knack.router.current_scene
  const pageExists = Object.prototype.hasOwnProperty.call(Knack.scenes._byId, redirectPage)

  checkAuth()

  function checkAuth() {
    if (scenesToExclude.includes(scene.key)) return

    const userAttributes = Knack.getUserAttributes()?.values
    const isUserAuthenticated = userAttributes?.[loginStateFieldKey] === authValue
    const shouldRedirect = pageExists && !isUserAuthenticated && currentPage !== redirectPage

    if (shouldRedirect) {
      Knack.Navigation.redirectToURL('#' + redirectPage)
      console.log(`User redirected to ${redirectPage} due to missing authentication.`)
    }
  }
})
2 Likes

Thanks so much, that looks like exactly what I needed. I’ll give it a try today, and once its in place I’ll package up the info of how my MFA solution works for anyone interested.

After a bit if fiddling I got it working perfectly, so thanks again for your contribution. I’ll be posting some instructions on how to implement the MFA tonight, and your code is in the heart of it.

1 Like