Commit 89f2aea0 authored by Kacprzak, Izabella's avatar Kacprzak, Izabella
Browse files

Added localStorage for saving a login token [BG, IK]

parent b77748ec
Pipeline #202455 passed with stage
in 1 minute and 9 seconds
......@@ -100,9 +100,9 @@ def user_login():
username, password = (request.json['username'], request.json['password'])
user = User.query.get(username)
if user == None:
return jsonify(status = "False")
return jsonify(token = "False")
if bcrypt.checkpw(password.encode('utf-8'), user.password.encode('utf-8')):
return jsonify(status = "True")
return jsonify(token = "True")
else:
return jsonify(status = "False")
\ No newline at end of file
return jsonify(token = "False")
\ No newline at end of file
......@@ -43,7 +43,7 @@ const AddUser = () => {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newUser)
}).then(() => {
history.push('/home');
history.push('/');
})
}
......
import React, { useState } from 'react';
import {HashRouter as Router, Route, Switch} from 'react-router-dom'
import Navbar from './Navbar'
import Home from './Home'
import CreateProject from './CreateProject'
import {HashRouter as Router, Route, Switch} from 'react-router-dom'
import ProjectDetails from './ProjectDetails'
import PageNotFound from './PageNotFound'
import MyProfile from './MyProfile'
......@@ -14,20 +16,25 @@ import EditUser from './EditUser'
import ProjectTasks from './ProjectTasks'
import AddProjectTask from './AddProjectTask'
import Login from './Login'
import useToken from './useToken';
function App() {
const title = "Dashboard"
const { token, setToken } = useToken();
const title = "Dashboard"
if(token != "True") {
return <Login setToken={setToken} />
}
return (
<Router>
<div className="App">
<Sidebar />
<Navbar />
<div className="content">
<Switch>
<Navbar />
<div className="content">
<Switch>
<Route exact path="/">
<Login />
</Route>
<Route exact path="/home">
<Home />
</Route>
<Route exact path="/create-project">
......
......@@ -21,7 +21,7 @@ const CreateProject = () => {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newProject)
}).then(() => {
history.push('/home');
history.push('/');
})
}
......
......@@ -26,7 +26,7 @@ const EditProject = () => {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(e)
}).then(() => {
history.push('/home');
history.push('/');
})
}
......
......@@ -32,7 +32,7 @@ const EditUser = () => {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(e)
}).then(() => {
history.push('/home');
history.push('/');
})
}
......
import { useState } from 'react';
import { useHistory } from "react-router-dom"
import useFetch from './useFetch'
const Login = ({ setToken }) => {
import PropTypes from 'prop-types';
async function loginUser(credentials) {
return fetch('/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(data => data.json())
}
export default function Login({ setToken }) {
const [username, setUserName] = useState();
const [password, setPassword] = useState();
const history = useHistory()
const handleSubmit = async e => {
e.preventDefault();
const credentials = {username, password}
fetch('/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(res => {
if (!res.ok) { // error coming back from server
throw Error('could not fetch the data for that resource');
}
return res.json();
})
.then(
data => {
if(data.status == "True") {
history.push('/home');
} else {
document.getElementsByClassName("incorrect-password")[0].style.display = "block";
}
})
const token = await loginUser({
username,
password
});
setToken(token);
}
return (
<div className="login">
<h2> Sign In </h2>
<form>
<form onSubmit={handleSubmit}>
<input type="text" id="login" class="fadeIn second" name="login" placeholder="login"
onChange={e => setUserName(e.target.value)}/>
<input type="text" id="password" class="fadeIn third" name="login" placeholder="password"
......@@ -52,7 +40,7 @@ const Login = ({ setToken }) => {
<div className="incorrect-password" style={{display: 'none'}}>
<h2 >Incorrect password!</h2>
</div>
<button onClick={handleSubmit}>Log In</button>
<button type="submit">Log In</button>
</form>
<div id="formFooter">
......@@ -62,4 +50,6 @@ const Login = ({ setToken }) => {
);
}
export default Login;
Login.propTypes = {
setToken: PropTypes.func.isRequired
}
import { Link } from 'react-router-dom'
const Navbar = () => {
if (window.location.pathname.match('/')){
return null;
}
return (
<nav className="navbar" >
<a href="/home" style={{
<a href="/" style={{
color: '#ff4e83',
fontSize: '20px',
borderRadius: '8px'
......
......@@ -5,7 +5,7 @@ const PageNotFound = () => {
<div className="page-not-found">
<h2>Something went wrong...</h2>
<p>That page cannot be found</p>
<Link to='/home'>Back to the main page</Link>
<Link to='/'>Back to the main page</Link>
</div>
);
}
......
......@@ -11,7 +11,7 @@ const ProjectDetails = () => {
const handleRemove = e => {
e.preventDefault()
fetch("/projects/" + id, { method: 'DELETE' })
.then(() => { history.push('/home'); })
.then(() => { history.push('/'); })
};
return (
......
......@@ -5,9 +5,6 @@ import { Link } from 'react-router-dom'
const slackLink = "https://slack.com/intl/en-gb/"
export default props => {
if (window.location.pathname.match('/')){
return null;
}
return (
<Menu>
<div className="menu-item" >
......
......@@ -11,7 +11,7 @@ const User = () => {
const handleRemove = e => {
e.preventDefault()
fetch("/users/" + username, {method: 'DELETE'})
.then(()=> {history.push('/home');})
.then(()=> {history.push('/');})
};
return (
......
import { useState } from 'react';
export default function useToken() {
const getToken = () => {
const tokenString = localStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token
};
const [token, setToken] = useState(getToken());
const saveToken = userToken => {
localStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};
return {
setToken: saveToken,
token
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment