Skip to content

Commit

Permalink
authentication and redux added
Browse files Browse the repository at this point in the history
  • Loading branch information
kazirafi71 committed May 4, 2021
1 parent 698b94c commit a58bc8e
Show file tree
Hide file tree
Showing 13 changed files with 163 additions and 35 deletions.
5 changes: 5 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"react-scripts": "4.0.3",
"react-toastify": "^7.0.4",
"redux": "^4.1.0",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.1.1"
},
Expand Down
47 changes: 40 additions & 7 deletions client/src/App.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,47 @@
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { BrowserRouter as Router, Route, Switch, useHistory } from "react-router-dom";
import DashBoard from './pages/DashBoard/Dashboard'
import Settings from './pages/Settings/Settings'
import Messages from './pages/Messages/Messages'
import Grades from "./pages/Grades/Grades";

import Profile from "./pages/Profile/Profile";
import Header from "./components/Header/Header";
import CourseInfo from "./pages/CourseInfo/CourseInfo";
import Login from "./pages/Login/Login";
import Register from "./pages/Register/Register";
import TeacherDashboard from "./pages/Teacher/TeacherDashboard/TeacherDashboard";
import AdminDashboard from "./pages/Admin/AdminDashboard/AdminDashboard";
import { useEffect } from "react";
import { useDispatch } from "react-redux";

function App() {
return <div className="App">
<Router>
<Header/>
<Switch>

const Routing=()=>{
const history=useHistory()
const dispatch=useDispatch()
const user=JSON.parse(localStorage.getItem("user"))
console.log(user)
useEffect(()=>{
if(!user){
history.push('/login')
}else{
dispatch({type:"SET__USER",payload:user})

}


},[])
return(
<Switch>
<Route exact path='/'>
<DashBoard/>
</Route>
<Route exact path='/teacher-dashboard'>
<TeacherDashboard/>
</Route>
<Route exact path='/admin-dashboard'>
<AdminDashboard/>
</Route>
<Route exact path='/messages'>
<Messages/>
</Route>
Expand All @@ -42,6 +64,17 @@ function App() {
<CourseInfo/>
</Route>
</Switch>

)
}



function App() {
return <div className="App">
<Router>
<Header/>
<Routing/>
</Router>
</div>;
}
Expand Down
20 changes: 20 additions & 0 deletions client/src/Redux/auth/authReducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { SET__USER } from "./authTypes";

const init = {
user: {},
};

const authReducer = (state = init, action) => {
switch (action.type) {
case SET__USER:
return {
user: action.payload,
};

default:
return state;
}
};


export default authReducer
2 changes: 2 additions & 0 deletions client/src/Redux/auth/authTypes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const SET__USER='SET__USER'
export const CLEAR__USER='CLEAR__USER'
Empty file added client/src/Redux/index.js
Empty file.
9 changes: 9 additions & 0 deletions client/src/Redux/rootReduer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { combineReducers } from "redux";
import authReducer from "./auth/authReducer";


const rootReducer=combineReducers({
auth: authReducer
})

export default rootReducer
8 changes: 8 additions & 0 deletions client/src/Redux/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { applyMiddleware, createStore } from 'redux'
import rootReducer from './rootReduer'
import Thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension';

const store=createStore(rootReducer,composeWithDevTools(applyMiddleware(Thunk)))

export default store
6 changes: 4 additions & 2 deletions client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {Provider} from 'react-redux'
import store from './Redux/store';


ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</React.StrictMode>,
</Provider>,
document.getElementById('root')
);

Expand Down
11 changes: 11 additions & 0 deletions client/src/pages/Admin/AdminDashboard/AdminDashboard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';

const AdminDashboard = () => {
return (
<div>
AdminDashboard
</div>
);
};

export default AdminDashboard;
69 changes: 46 additions & 23 deletions client/src/pages/Login/Login.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import Styles from './login.module.css'
import Styles from "./login.module.css";
import { Button, Container, Paper, Typography } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import { Col, Form, Row } from "react-bootstrap";
import Alert_Comp from "../../components/Alert/Alert_Comp";
import Spinner_comp from "../../components/Spinner/Spinner_comp";
import Toast_Comp from "../../components/Toast/Toast_Comp";
import { Link, useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";

const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

const [error, setError] = useState();
const [loading, setLoading] = useState(false);
const [toast, setToast] = useState(false);
const history = useHistory();
const [email, setEmail] = useState("[email protected]");
const [password, setPassword] = useState("123456");
const [error, setError] = useState();
const [loading, setLoading] = useState(false);
const [toast, setToast] = useState(false);
const history = useHistory();
const {user} = useSelector((state) => state.auth);
//console.log(user);

const dispatch = useDispatch();


const formSubmitHandler = (e) => {
e.preventDefault();
setLoading(true);
Expand All @@ -26,33 +29,52 @@ const Login = () => {
"Content-Type": "application/json",
},
body: JSON.stringify({

email,
password,

}),
})
.then((res) => res.json())
.then((result) => {
setLoading(false);
console.log(result);
// console.log(result);
if (result.errors) {
setError(result.errors);
} else {
dispatch({ type: "SET__USER", payload: result.userInfo });
localStorage.setItem("auth_token", result.token);
localStorage.setItem("user", JSON.stringify(result.userInfo));
setToast(true);
setError(null);
// setTimeout(() => {
// history.push("/");
// }, 3000);
// clearTimeout();
// setError(null);
// setTimeout(() => {
// history.push("/");
// }, 3000);
// clearTimeout();
}
})
.catch((err) => {
console.log(err);
});
};
return (
<div style={{ fontFamily: "Poppins" }}>

useEffect(() => {
console.log(user)
console.log(user.role)
if(user && user.role=="Student")
{
history.push('/')
}
else if(user && user.role==="Admin")
{
history.push('/admin-dashboard')
}
else if(user && user.role==="Teacher")
{
history.push('/teacher-dashboard')
}

}, [user]);
return (
<div style={{ fontFamily: "Poppins" }}>
<Container>
<Toast_Comp
setToast={setToast}
Expand All @@ -74,10 +96,10 @@ const Login = () => {
)}

<Form onSubmit={formSubmitHandler}>

<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control
value={email}
onChange={(e) => setEmail(e.target.value)}
type="email"
placeholder="Enter email"
Expand All @@ -87,6 +109,7 @@ const Login = () => {
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
placeholder="Password"
Expand All @@ -95,7 +118,7 @@ const Login = () => {
{error && error.password}
</span>
</Form.Group>

<Typography style={{ color: "GrayText" }} variant="subtitle2">
Don't Have an account?
<Link to="/register">Register Here</Link>
Expand All @@ -114,7 +137,7 @@ const Login = () => {
</Row>
</Container>
</div>
);
);
};

export default Login;
export default Login;
11 changes: 11 additions & 0 deletions client/src/pages/Teacher/TeacherDashboard/TeacherDashboard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';

const TeacherDashboard = () => {
return (
<div>
TeacherDashboard
</div>
);
};

export default TeacherDashboard;
9 changes: 6 additions & 3 deletions controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ module.exports.login__controller = async (req, res, next) => {
try {
const { email, password } = req.body;

const userInfo = await UserModel.findOne({ email });
const userInfo = await (await UserModel.findOne({ email }));

if (!userInfo) {
return res.status(401).json({
Expand All @@ -60,9 +60,12 @@ module.exports.login__controller = async (req, res, next) => {
errors: { password: "password not matched" },
});
}
const token = jwt.sign({ _id: userInfo._id }, SECRET_KEY);

userInfo.password=undefined

const token = jwt.sign({ _id: userInfo._id,name: userInfo.userName,email: userInfo.email,role: userInfo.role }, SECRET_KEY);
return res.status(200).json({
text: "Login successful",
userInfo,
token,
});
})
Expand Down

0 comments on commit a58bc8e

Please sign in to comment.