Skip to content

Commit 3a8ebb3

Browse files
segregate and protect routes for both user and admin
1 parent a1416c7 commit 3a8ebb3

File tree

5 files changed

+54
-3
lines changed

5 files changed

+54
-3
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import React ,{useState,useEffect} from "react";
2+
import Router from "next/router";
3+
import {isAuthenticated} from "../../actions/authentication";
4+
5+
const Admin = ({children})=>{
6+
7+
8+
useEffect(()=>{
9+
if(!isAuthenticated()){
10+
Router.push(`/login`);
11+
}else if (isAuthenticated().role !== 1){
12+
Router.push(`/`);
13+
}
14+
},[])
15+
16+
return (
17+
<>
18+
{children}
19+
</>
20+
)
21+
22+
}
23+
24+
export default Admin;

client/components/authentication/LoginAuth.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ const LoginAuth = () => {
3131
// authenticate the user
3232
authenticate(data,()=>{
3333
if(isAuthenticated() && isAuthenticated().role === 1){
34-
Router.push(`/admin`)
34+
Router.push(`/adminDashboard`)
3535
} else {
36-
Router.push(`/user`)
36+
Router.push(`/userDashboard`)
3737
}
3838
})
3939

@@ -54,7 +54,6 @@ const LoginAuth = () => {
5454
return (
5555

5656
<form onSubmit={handleSubmit}>
57-
5857
{/* Email */}
5958
<div className="form-group">
6059
<input type="email" value={email} className="form-control" onChange={handleChange("email")} placeholder="Enter your @Email address"/>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import React ,{useState,useEffect} from "react";
2+
import Router from "next/router";
3+
import {isAuthenticated} from "../../actions/authentication";
4+
5+
const PrivateRoute = ({children})=>{
6+
7+
8+
useEffect(()=>{
9+
if(!isAuthenticated()){
10+
Router.push(`/login`)
11+
}
12+
},[])
13+
14+
return (
15+
<>
16+
{children}
17+
</>
18+
)
19+
20+
}
21+
22+
export default PrivateRoute;

client/pages/adminDashboard/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import Layout from "../../components/Layout";
2+
import Admin from "../../components/authentication/Admin";
23
import Link from "next/link";
34

45

56
const AdminIndex =() =>{
67
return(
78
<Layout>
9+
<Admin>
810
<h2>Admin Dashboard</h2>
11+
</Admin>
912
</Layout>
1013
)
1114
}

client/pages/userDashboard/index.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import Layout from "../../components/Layout";
2+
import PrivateRoute from "../../components/authentication/PrivateRoute";
23
import Link from "next/link";
34

45

56
const UserIndex =() =>{
67
return(
78
<Layout>
9+
<PrivateRoute>
810
<h2>User Dashboard</h2>
11+
</PrivateRoute>
912
</Layout>
1013
)
1114
}

0 commit comments

Comments
 (0)