Skip to content

Commit d44e4c4

Browse files
committed
feat(rbac): refactor and multiple accessRoutes feature for RBAC added
BREAKING CHANGE: you must define an accessRoute for each role defined
1 parent f80f1da commit d44e4c4

File tree

3 files changed

+21
-18
lines changed

3 files changed

+21
-18
lines changed

src/components/NextShield.tsx

+5-17
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { ReactNode, useEffect } from 'react'
22

33
import { NextShieldProps } from '../types/props'
4-
import { verifyPath } from '../libs/routes'
4+
import { getAccessRoute, verifyPath } from '../libs/routes'
55

66
/**
77
* 😉 The shield that every Next.js project needs
@@ -66,23 +66,11 @@ export function NextShield<
6666

6767
useEffect(() => {
6868
if (!isAuth && !isLoading && pathIsPrivate) replace(loginRoute)
69-
if (isAuth && !isLoading && pathIsPublic) {
70-
if (typeof accessRoute !== 'undefined') {
71-
replace(accessRoute)
72-
}
73-
if (RBAC && userRole) {
74-
replace(RBAC[userRole].accessRoute)
75-
}
76-
}
69+
if (isAuth && !isLoading && pathIsPublic)
70+
getAccessRoute(RBAC, userRole, accessRoute, loginRoute)
7771

78-
if (isAuth && userRole && !isLoading && !pathIsHybrid && !pathIsAuthorized) {
79-
if (typeof accessRoute !== 'undefined') {
80-
replace(accessRoute)
81-
}
82-
if (RBAC && userRole) {
83-
replace(RBAC[userRole].accessRoute)
84-
}
85-
}
72+
if (isAuth && userRole && !isLoading && !pathIsHybrid && !pathIsAuthorized)
73+
getAccessRoute(RBAC, userRole, accessRoute, loginRoute)
8674
}, [
8775
replace,
8876
userRole,

src/libs/routes.ts

+15
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1+
import { RoleAccess } from '../types/props'
2+
13
export function verifyPath(routes: string[] | undefined, uri: string) {
24
return routes?.some(route => route === uri)
35
}
6+
7+
export function getAccessRoute(
8+
RBAC: RoleAccess<string[]> | undefined,
9+
userRole: string | undefined,
10+
accessRoute: string | undefined,
11+
loginRoute: string
12+
) {
13+
if (typeof accessRoute !== 'undefined') return accessRoute
14+
15+
if (RBAC && userRole) return RBAC[userRole].accessRoute
16+
17+
return loginRoute
18+
}

src/types/props.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { ReactNode } from "react";
22
import type { NextRouter } from 'next/router'
33

4-
type RoleAccess<Routes extends string[]> = {
4+
export type RoleAccess<Routes extends string[]> = {
55
[index: string]: {
66
grantedRoutes: Routes,
77
accessRoute: Routes[number]

0 commit comments

Comments
 (0)