浏览代码

token auth route fix

amenpunk 2 年之前
父节点
当前提交
f9b638b990
共有 3 个文件被更改,包括 50 次插入5 次删除
  1. 42 3
      src/Components/PrivateRoute.js
  2. 4 1
      src/Pages/Login.jsx
  3. 4 1
      src/Pages/Logincs.jsx

+ 42 - 3
src/Components/PrivateRoute.js

@@ -1,15 +1,54 @@
1 1
 import { Navigate, useLocation } from 'react-router-dom';
2
-// import useAuth from '../Auth/useAuth';
3 2
 import { useSelector } from 'react-redux';
3
+import jwt_decode from "jwt-decode";
4
+
5
+const Recluter = {
6
+  authorities: "Reclutador",
7
+  app_name: 'Dashboard',
8
+  type: 1
9
+}
10
+
11
+const User = {
12
+  authorities: "User",
13
+  app_name: 'User',
14
+  type: 2
15
+}
4 16
 
5 17
 export function RequireToken({ children }) {
6 18
 
7 19
   let token = useSelector((state) => state.token.token)
8 20
   let location = useLocation();
21
+  let app_name = children?.type?.name
9 22
 
10 23
   if (!token) {
11
-    console.log('falta authorizacion user')
12
-    return <Navigate to="/logincd" state={{ from: location }} replace />;
24
+    if (app_name === Recluter.app_name) {
25
+      return <Navigate to="/login" state={{ from: location }} replace />;
26
+    } else {
27
+      return <Navigate to="/logincd" state={{ from: location }} replace />;
28
+    }
29
+  } else {
30
+
31
+    let body_token = jwt_decode(token);
32
+    let token_access = body_token?.authorities;
33
+
34
+    if (app_name === User.app_name) {
35
+      let valid_user = token_access.includes(User.authorities);
36
+      if (!valid_user) {
37
+        return <Navigate to="/logincd" state={{ from: location }} replace />;
38
+      } else {
39
+        return children;
40
+      }
41
+    }
42
+
43
+    if (app_name === Recluter.app_name) {
44
+      let valid_user = token_access.includes(Recluter.authorities);
45
+      if (!valid_user) {
46
+        return <Navigate to="/logincd" state={{ from: location }} replace />;
47
+      } else {
48
+        return children;
49
+      }
50
+    }
51
+
13 52
   }
14 53
 
15 54
   return children;

+ 4 - 1
src/Pages/Login.jsx

@@ -96,7 +96,10 @@ export function Login() {
96 96
   
97 97
   React.useEffect(() => {
98 98
     if(auth.token){
99
-      navigate('/dashboard/home')
99
+      let body_token = jwt_decode(auth.token);
100
+      if(body_token.authorities.includes("Reclutador")){
101
+        navigate('/dashboard/home')
102
+      }
100 103
     }
101 104
   }, [auth, navigate])
102 105
 

+ 4 - 1
src/Pages/Logincs.jsx

@@ -45,7 +45,10 @@ export function LoginCs() {
45 45
 
46 46
   React.useEffect(() => {
47 47
     if(token){
48
-      navigate('/user/home')
48
+      let body_token = jwt_decode(token);
49
+      if(body_token.authorities.includes("User")){
50
+        navigate('/user/home')
51
+      }
49 52
     }
50 53
   }, [token, navigate])
51 54