Skip to content

Commit

Permalink
local session added
Browse files Browse the repository at this point in the history
  • Loading branch information
Luxshan2000 committed Oct 2, 2023
1 parent 254dc0c commit 2984dde
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 27 deletions.
24 changes: 21 additions & 3 deletions backend/src/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,12 @@ exports.login = async (req, res) => {
const token = jwt.sign({ name: user.name, isVerified: user.isVerified }, process.env.SECURITY_KEY, { expiresIn: '5hour' });


res.cookie("token", token);

const oneWeekInSeconds = 7 * 24 * 60 * 60; // 7 days * 24 hours * 60 minutes * 60 seconds
const expirationDate = new Date(Date.now() + oneWeekInSeconds * 1000); // Convert seconds to milliseconds
res.cookie('token', token, {
expires: expirationDate,

});
// Send the token in the response
res.json({ message: 'Login successful' });
} catch (error) {
Expand Down Expand Up @@ -202,4 +206,18 @@ exports.facebooklogin = async ( req,res) => {
exports.googleLoginApp = async (req,res) => {
const { token } = req.body

}
}


exports.logout = async (req,res) =>{
try{
res.clearCookie('token')
res.json({msg:"Done"})
}
catch(err){
res.error(err)
}

}


3 changes: 3 additions & 0 deletions backend/src/routes/authRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@ router.post('/login', authController.login);
router.post('/googleLogin',authController.googleLogin)
router.post('/loginApp', authController.loginApp);
router.post('/facebooklogin',authController.facebooklogin);
router.post('/logout', authController.logout);



module.exports = router;
3 changes: 2 additions & 1 deletion webapp/src/components/UserInfo.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import { Link } from 'react-router-dom'
import { logout } from '../utils/logout'
function UserInfo({showProfile}) {
return (
<div
Expand Down Expand Up @@ -31,7 +32,7 @@ function UserInfo({showProfile}) {
<hr/>
<ul className="nav nav-pills flex-column mb-auto">
<li>
<Link to="/" className="nav-link text-dark">
<Link onClick={logout} className="nav-link text-dark">
<i class="bi bi-box-arrow-in-right pe-2"></i>
Log out
</Link>
Expand Down
6 changes: 1 addition & 5 deletions webapp/src/context/AuthContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ export const useAuthContext = () => useContext(AuthContext)
//create provider
export const AuthProvider = ({children})=>{
//Todo
const [auth,setAuth] = useState({
name:'UserName',
isVerified:true,
token:"dummy"
})
const [auth,setAuth] = useState(null)

return (
<AuthContext.Provider value={{ auth, setAuth}}>
Expand Down
13 changes: 11 additions & 2 deletions webapp/src/routes/PrivateRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@ import { Outlet, Navigate} from "react-router-dom";

import React from 'react'
import { useAuthContext } from "../context/AuthContext";
import { getSessionCookie } from "../utils/cookie";


function PrivateRoutes() {
const {auth}= useAuthContext()


let allow = false

allow = getSessionCookie("token")



return (
auth.token ? <Outlet/> : <Navigate to='/' replace={true}/>
allow ? <Outlet/> : <Navigate to='/' replace={true}/>
)
}

Expand Down
17 changes: 17 additions & 0 deletions webapp/src/utils/logout.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react'
import axios from 'axios';

export const logout = () => {
axios.defaults.withCredentials = true
console.log("clciked")
// Add logout functionality here
axios.post("http://localhost:5000/api/auth/logout")
.then((res)=>{
window.location.reload(true);
window.location.href = "/";
}).catch((err)=>console.log(err))
};




44 changes: 33 additions & 11 deletions webapp/src/views/Login.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useState } from "react";
import FloatingLabel from 'react-bootstrap/FloatingLabel';
import Form from 'react-bootstrap/Form';
import '../assets/CSS/signUp.css'
Expand All @@ -11,21 +11,43 @@ import jwt_decode from 'jwt-decode'

export default function Login() {
const navigate = useNavigate()
const {setAuth,auth} = useAuthContext()

const [email,setEmail] = useState("")
const [password,setPassword] = useState("")




const handleSubmit = ()=>{

const handleSubmit = (e)=>{
e.preventDefault()

axios.defaults.withCredentials = true
axios.post('http://localhost:5000/api/auth/login', {email:"[email protected]", password:"pwd123"})
axios.post('http://localhost:5000/api/auth/login', {email:email, password:password})
.then(response => {
// Handle the successful response here

console.log(jwt_decode(getSessionCookie("token")))
console.log('Registration successful:', response.data);
setAuth(true)

if(jwt_decode(getSessionCookie("token")).isVerified){
navigate("/dashboard",{replace:true})
}
else{
navigate("/dashboard",{replace:true})
}




})
.catch(error => {
// Handle any errors that occur during the request
console.error('Registration failed:', error.response.data);
});
console.log('Login failed!')
}).finally(()=>{
setEmail("")
setPassword("")
})


// if(auth.isVerified){
Expand All @@ -40,15 +62,15 @@ export default function Login() {
<div className="container-fluid" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<div className="blurEffect" style={{ width: '500px' }}>
<h1 className="mb-4" style={{textAlign:'center'}}>LOGIN</h1>
<Form>
<Form onSubmit={handleSubmit}>

<FloatingLabel
controlId="floatingInput"
label="Email address"
className="mb-3"
style={{ fontSize: 'small' }}
>
<Form.Control type="email" size="sm" placeholder="[email protected]" />
<Form.Control onChange={(e)=>setEmail(e.target.value)} value={email} type="email" size="sm" placeholder="[email protected]" />
</FloatingLabel>

<FloatingLabel
Expand All @@ -57,7 +79,7 @@ export default function Login() {
// className="mb-3"
style={{ fontSize: 'small' }}
>
<Form.Control type="password" placeholder="Password" />
<Form.Control onChange={(e)=>setPassword(e.target.value)} value={password} type="password" placeholder="Password" />
</FloatingLabel>


Expand All @@ -68,7 +90,7 @@ export default function Login() {
</div>

<div style={{ display: 'flex', flexDirection: 'column',marginTop: '50px'}}>
<Button onClick={handleSubmit} className="mb-3 task-button">Login</Button>
<Button type="submit" className="mb-3 task-button">Login</Button>
{/* <hr className="hr-lines"/>
<p>OR</p> */}
<p className="hr-line"><span>OR</span></p>
Expand Down
16 changes: 11 additions & 5 deletions webapp/src/views/SignUp.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,16 @@ export default function SignUp() {
const [conpassword, setConPassword] = useState("")


const handleRegister = ()=>{
const handleRegister = (e)=>{
e.preventDefault()
if(password != conpassword){
return
}

axios.post('http://localhost:5000/api/auth/signup', {email:email, password:password, name:userName})
.then(response => {
// Handle the successful response here
console.log('Registration successful:', response.data);
console.log('Registration successful!', response.data);

// navigate("/passwordverify", { replace: true });

Expand All @@ -33,15 +34,20 @@ export default function SignUp() {
})
.catch(error => {
// Handle any errors that occur during the request
console.error('Registration failed:', error.response.data);
console.log('Registration failed!');
}).finally(()=>{
setUserName("")
setEmail("")
setPassword("")
setConPassword("")
})
}

return (
<div className="container-fluid m-5" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center',height:'100vh' }}>
<div className="blurEffect" style={{ width: '500px' }}>
<h1 className="mb-4" style={{textAlign:'center'}}>SIGN-UP</h1>
<Form>
<Form onSubmit={handleRegister}>
<FloatingLabel
controlId="floatingInput"
label="Name"
Expand Down Expand Up @@ -81,7 +87,7 @@ export default function SignUp() {
</FloatingLabel>

<div style={{ display: 'flex', flexDirection: 'column' }}>
<Button onClick={handleRegister} type='submit' className="mb-3 task-button">Sign Up</Button>
<Button type='submit' className="mb-3 task-button">Sign Up</Button>
<p className="hr-line"><span>OR</span></p>

<GoogleLoginButton/>
Expand Down

0 comments on commit 2984dde

Please sign in to comment.