Skip to content

Commit 1b8009d

Browse files
committed
update auth.tsx
1 parent 06a1ad2 commit 1b8009d

File tree

1 file changed

+30
-26
lines changed

1 file changed

+30
-26
lines changed

MyApp.Client/src/lib/auth.tsx

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { useEffect } from "react"
22
import { useNavigate, useLocation } from "react-router-dom"
33
import { useAuth, Loading } from "@servicestack/react"
4-
import { client, Routes } from "./gateway"
4+
import { client, isServerRoute, Routes } from "./gateway"
55
import { Authenticate } from "@/lib/dtos"
66

77
export const Redirecting = () => {
@@ -14,37 +14,41 @@ type ValidateAuthProps = {
1414
redirectTo?: string
1515
}
1616
export 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

5054
export function appAuth() {

0 commit comments

Comments
 (0)