11import React , { useEffect } from "react"
22import { useNavigate , useLocation } from "react-router-dom"
33import { useAuth , Loading } from "@servicestack/react"
4- import { client , Routes } from "./gateway"
4+ import { client , isServerRoute , Routes } from "./gateway"
55import { Authenticate } from "@/lib/dtos"
66
77export const Redirecting = ( ) => {
@@ -14,37 +14,41 @@ type ValidateAuthProps = {
1414 redirectTo ?: string
1515}
1616export function ValidateAuth < TOriginalProps extends { } > ( Component :React . FC < TOriginalProps > , validateProps ? :ValidateAuthProps ) {
17- let { role, permission, redirectTo } = validateProps ?? { }
18- const compWithProps : React . FC < TOriginalProps > = ( props ) => {
19- const navigate = useNavigate ( )
20- const authProps = useAuth ( )
21- const { user, isAuthenticated, hasRole } = authProps
22- const location = useLocation ( )
23- useEffect ( ( ) => {
24- const goTo = shouldRedirect ( )
25- if ( goTo ) {
26- navigate ( goTo , { replace :true } )
27- }
28- } , [ user ] )
17+ let { role, permission, redirectTo } = validateProps ?? { }
18+ const compWithProps : React . FC < TOriginalProps > = ( props ) => {
19+ const navigate = useNavigate ( )
20+ const location = useLocation ( )
21+ const authProps = useAuth ( )
22+ const { user, isAuthenticated, hasRole } = authProps
23+ useEffect ( ( ) => {
24+ const goTo = shouldRedirect ( )
25+ if ( goTo ) {
26+ if ( isServerRoute ( goTo ) ) {
27+ window . location . href = goTo
28+ } else {
29+ navigate ( goTo , { replace : true } )
30+ }
31+ }
32+ } , [ user ] )
2933
30- redirectTo ??= location . pathname
34+ redirectTo ??= location . pathname
3135
32- const shouldRedirect = ( ) => ! isAuthenticated
33- ? Routes . signin ( redirectTo )
34- : role && ! hasRole ( role )
35- ? Routes . forbidden ( )
36- : permission && ! hasRole ( permission )
36+ const shouldRedirect = ( ) => ! isAuthenticated
37+ ? Routes . signin ( redirectTo )
38+ : role && ! hasRole ( role )
3739 ? Routes . forbidden ( )
38- : null ;
40+ : permission && ! hasRole ( permission )
41+ ? Routes . forbidden ( )
42+ : null ;
3943
40- if ( shouldRedirect ( ) ) {
41- return < Redirecting />
42- }
44+ if ( shouldRedirect ( ) ) {
45+ return < Redirecting />
46+ }
4347
44- return < Component { ...props } />
45- }
48+ return < Component { ...props } />
49+ }
4650
47- return compWithProps
51+ return compWithProps
4852}
4953
5054export function appAuth ( ) {
0 commit comments