I learn a bit of React. It's time to login for users. But there was a problem.
To get started, the code:
App.js
import React, {useState} from "react";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";
import PrivateRoute from './PrivateRoute';
import Home from './Home';
import Login from "./Login";
import { AuthContext } from "./Auth";
function App(props) {
const [authTokens, setAuthTokens] = useState(localStorage.getItem("tokens") || "");
const setTokens = (data) => {
localStorage.setItem("tokens", JSON.stringify(data));
setAuthTokens(data);
}
return (
<AuthContext.Provider value={{ authTokens, setAuthTokens: setTokens }}>
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
</ul>
<PrivateRoute exact path="/" component={Home} />
<Route path="/login" component={Login} />
</div>
</Router>
</AuthContext.Provider>);
}
export default App;
Login.js
import React, { useState } from "react";
import { Link, Redirect } from 'react-router-dom';
import axios from 'axios';
import { useAuth } from "./Auth";
function Login(props) {
const [isLoggedIn, setLoggedIn] = useState(false);
const [isError, setIsError] = useState(false);
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const { setAuthTokens } = useAuth();
const referer = props.location.state ? props.location.state.referer : '/';
function postLogin() {
axios.post("https://myapi.com/login.php", {
userName,
password
}).then(result => {
if (result.status === 200) {
setAuthTokens(result.data);
setLoggedIn(true);
console.log(result.data);
} else {
setIsError(true);
}
}).catch(e => {
setIsError(true);
console.log(e);
});
}
if (isLoggedIn) {
return <Redirect to={referer} />;
}
return (
<input type="username" value={userName} onChange={e=>{ setUserName(e.target.value); }} placeholder="username"
/>
<input type="password" value={password} onChange={e=>{ setPassword(e.target.value); }} placeholder="password"
/>
<input type="submit" onClick={postLogin}>Sign In</Button>
{ isError&& <div>The username or password provider were incorrect.</div>}
);
}
export default Login;
Auth.js
import { createContext, useContext } from 'react';
export const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext);
}
PrivateRoute.js
import React from 'react'
import { Redirect, Route } from 'react-router-dom'
import { useAuth } from "./Auth";
const PrivateRoute = ({ component: Component, ...rest }) => {
const { authTokens } = useAuth();
return (
<Route
{...rest}
render={props =>
authTokens ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/login", state: { referer: props.location } }} />
)
}
/>
);
}
export default PrivateRoute
At login, everything works well. But when I try to log in to /login again, it doesn’t throw me back to the referer page. Although it should, otherwise why would the user once again see the login page, if he is already logged in.
Is it possible to store LocalStorage, such as cookies, for 30 days?
If possible, please explain the logic of logging in to react.
I understand it this way (correct if I am mistaken):
user enters login and password
in response, I send a TOKEN (if the username and password on the server side match)
I load this token, for example in Mysql, store it there.
the next time I log on to the site, I check if there is a token in the Mysql database (if so, leave it logged in - if not, then delete the row from the database and throw it on the login page).
Right?)
Right :
when you submit your login credentials like username and password then you are getting token from your server then you have to store your token in your local-storage or as cookie like token : Your_token
Then in your router in your App.js check if you are having token or not like
{
!localStorage.getItem('token') ? <Redirect from='/' to='/login' /> : ''
}
Here if you don't have your token then you are redirecting to login else redirecting to your following page.
You can use your token as header in api calls and then you can check if your token is valid or not from your back-end if not then return with error message.
If your token is expire then you can set your token : ' ' in localstorage .Then you can redirect to login page from that api response.
Main thing is token create token which automatically expire as per your requirement and use it with local-storage or cookie.
Related
I met a problem which I cannot solve.. I have register, login authentification and logout. So I noticed that if I refresh my page user is no longer logged in. So I found a solution for it, is using localstorage, of course there's more option how to solve it, but this one is more understandable to me. But as I expected I'm stuck with it, cause of useEffect() which is not my strongest side. So I hope you guys can help me with that. Of course I tried it without it, but than got some "red" color in my code (errors).
There's my code:
This is what I'm using in App.js. There I'm creating a variable window.localStorage with getItem and adding it to MainContext:
function App() {
// Use states
const [user, setUser] = useState(null);
const [message, setMessage] = useState('');
const isLoggedIn = window.localStorage.getItem('isLoggedIn')
// Main context
const states = { user, setUser, message, setMessage, isLoggedIn };
// Side effects
return (
<div className='App'>
<MainContext.Provider value={states}>
<BrowserRouter>
<Routes>
<Route path='/' element={isLoggedIn ? <HomePage /> : <LoginPage />}></Route>
{!user && <Route path='/register' element={<RegisterPage />}></Route>}
{!user && <Route path='/login' element={<LoginPage />}></Route>}
</Routes>
</BrowserRouter>
</MainContext.Provider>
</div>
);
}
export default App;
This is my Login component at the end of login I'm setting localstorage when Login button is clicked:
import React, { useContext, useRef } from 'react';
import MainContext from '../context/MainContext';
import { post } from '../helper/helper';
import { useNavigate } from 'react-router-dom';
export default function Login() {
const nav = useNavigate()
const { message, setMessage, setUser } = useContext(MainContext);
// Setting inputs references
const usernameRef = useRef();
const passwordRef = useRef();
const login = async () => {
// Setting a user for sign in, taking input values
const user = {
username: usernameRef.current.value,
password: passwordRef.current.value,
};
// Posting sign in user to database, if all fields validated (successfully signin), if failed (getting error message)
const result = await post(user, 'login');
if (!result.error) {
setMessage(result.message);
usernameRef.current.value = '';
passwordRef.current.value = '';
setUser(result.data);
} else {
setMessage(result.message);
}
window.localStorage.setItem('isLoggedIn', true)
nav('/')
};
return (
<div className='login'>
<h2>Sign In!</h2>
{message !== '' && <p className='signin__message'>{message}</p>}
<input ref={usernameRef} onClick={() => setMessage('')} type='text' placeholder='Enter Username' />
<input ref={passwordRef} onClick={() => setMessage('')} type='password' placeholder='Enter Password' />
<button onClick={login}>Sign In</button>
</div>
);
}
In Toolbar(header) component I wanna show is user is logged in, than I will show his username and avatar picture in right corner with logout button near it. If user not logged in or logout than in that place will be Login and Register buttons.
{isLoggedIn && <UserTrigger />}
{!isLoggedIn && <NoUser />}
There's user logout logic. If user click on logout button, than window.localStorage.removeItem
import React, { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import MainContext from '../context/MainContext';
export default function UserTrigger() {
const { user, setMessage, setUser } = useContext(MainContext);
const nav = useNavigate();
return (
<div className='toolbar__user'>
<div className='user'>
<img src={user.image} alt="" />
<h2>{user.username}</h2>
</div>
<div className='toolbar__logout'>
<button onClick={() => { setMessage(''); setUser(null); nav('/'); window.localStorage.removeItem('isLoggedIn') }}>
Logout
</button>
</div>
</div>
);
}
I wanna say sorry for that much code. But I wanna make sure that you'll understand it well. And thank you for any answers! <3
I am making a site whereby after the user signs in, the user is meant to be redirected to the home page. The homepage and all the other pages of the site are only accessible by signed in users but even after a user signs in(firebase auth), the rest of the site(protected routes) is still not accessible and the only page accessible is the login page. The technologies I am using are react, react router dom and firebase and this is how my code looks like, starting with the App.js
import Home from "./pages/home/Home";
import Login from "./pages/login/Login";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import List from "./pages/list/List";
import User from "./pages/user/User";
import AddNew from "./pages/addnew/AddNew";
import { useContext } from "react";
import { AuthContext } from "./context/AuthContext";
function App() {
const {currentUser} = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/login" exact element={<Login />} />
<Route path="/" exact element={ <RequireAuth> <Home /> </RequireAuth> } />
<Route path="/users" exact element={<RequireAuth><List /></RequireAuth>} />
<Route path="/users/:id" exact element={<RequireAuth><User /></RequireAuth>} />
<Route path="/add" exact element={<RequireAuth><AddNew /></RequireAuth>} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
And then followed by the login.js page
import React,{useState} from 'react'
import { useContext } from 'react';
import { signInWithEmailAndPassword } from "firebase/auth";
import { auth } from '../../firebase';
import "./login.css";
import {useNavigate} from "react-router-dom";
import { AuthContext } from '../../context/AuthContext';
export default function Login() {
const [error, seterror] = useState(false);
const [email, setemail] = useState("");
const [password, setpassword] = useState("");
const navigate = useNavigate();
const {dispatch} = useContext(AuthContext)
const handleLogin = (e) => {
e.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
dispatch({type: "LOGIN", payload: user});
navigate("/");
})
.catch((error) => {
seterror(true);
console.log(error.message);
});
}
return (
<div className='login'>
<form onSubmit={handleLogin}>
<input className='ok' type="email" placeholder='email' onChange={e => setemail(e.target.value)} />
<input className='ok' type="password" placeholder='password' onChange={e => setpassword(e.target.value)} />
<button className='sb'>Submit</button>
{error && <span className='ks'>Wrong email or password</span>}
</form>
</div>
)
}
And then I have the authreducer.js file that deals with the state
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN": {
return {
currentUser: action.payload,
}
}
case "LOGOUT": {
return {
currentUser: null
}
}
default:
return state;
}
}
export default AuthReducer
And finally the authcontext.js file
import { createContext, useEffect, useReducer } from "react";
import AuthReducer from "./AuthReducer";
const INITIAL_STATE = {
currentUser: JSON.parse(localStorage.getItem("user")) || null,
}
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({children}) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.currentUser))
}, [state.currentUser])
return (
<AuthContext.Provider value={{current: state.current, dispatch}}>
{children}
</AuthContext.Provider>
)
}
I do not know what could be causing this problem but I have an idea that it has something to do with the state because it was redirecting well before I started combining it with the state. What could be the problem
Issue
From that I can see, the App isn't destructuring the correct context value to handle the conditional route protection.
The AuthContextProvider provides a context value with current and dispatch properties
<AuthContext.Provider value={{ current: state.current, dispatch }}>
{children}
</AuthContext.Provider>
but App is accessing a currentUser property, which is going to be undefined because state.current is undefined.
const { currentUser } = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
The Navigate component will always be rendered.
Solution
Assuming the handleLogin handler correctly updates the state then the solution is to be consistent with state properties.
<AuthContext.Provider value={{ currentUser: state.currentUser, dispatch }}>
{children}
</AuthContext.Provider>
...
const { currentUser } = useContext(AuthContext);
const RequireAuth = ({ children }) => {
return currentUser ? children : <Navigate to="/login" />;
};
I am following the tutorial here:
https://github.com/auth0-blog/auth0-react-sample
I have most of the authentication working but get the following issue:
The first time I log in (after a cache clear) it asks me for gmail username. If I select the appropriate one, it logs me in. If I logout, and click login it never asks me again, it just uses the original one I entered.
If I enter an invalid gmail, it doesn't login but never asks again.
Either way, I suspect it's using the original response that it gets back (either authenticated or not).
Is there a way I can change it so that if I click the logout button (or it fails to login) it deletes the response.
I believe this post from 2018 is similar but I'm not sure how to modify it to today:
https://community.auth0.com/t/does-not-show-user-login-prompt-anymore-after-the-first-logging-in/16504
I'm new to react/auth0 but here are what I think to be the relevant files:
auth0-provider-with-history.js
import React from "react";
import { useHistory } from "react-router-dom";
import { Auth0Provider } from "#auth0/auth0-react";
const Auth0ProviderWithHistory = ({ children }) => {
const history = useHistory();
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID;
const audience = process.env.REACT_APP_AUTH0_AUDIENCE;
const onRedirectCallback = (appState) => {
history.push(appState?.returnTo || window.location.pathname);
};
return (
<Auth0Provider
domain={domain}
clientId={clientId}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
audience={audience}
>
{children}
</Auth0Provider>
);
};
export default Auth0ProviderWithHistory;
protected-route.js
// src/auth/protected-route.js
import React from "react";
import { Route } from "react-router-dom";
import { withAuthenticationRequired } from "#auth0/auth0-react";
import { Loading } from "../components/index";
const ProtectedRoute = ({ component, ...args }) => (
<Route
component={withAuthenticationRequired(component, {
onRedirecting: () => <Loading />,
})}
{...args}
/>
);
export default ProtectedRoute;
login-button.js
import React from "react";
import { useAuth0 } from "#auth0/auth0-react";
const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
return (
<button
className="btn btn-primary btn-block"
onClick={() => loginWithRedirect()}
>
Log In
</button>
);
};
export default LoginButton;
logout-button.js
import React from "react";
import { useAuth0 } from "#auth0/auth0-react";
const LogoutButton = () => {
const { logout } = useAuth0();
return (
<button
className="btn btn-danger btn-block"
onClick={() =>
logout({
returnTo: window.location.origin,
})
}
>
Log Out
</button>
);
};
export default LogoutButton;
I am not sure if this is the best way to do it, but I was able to get this working by adding localStorage.clear(); in appropriate locations to delete anything that was stored.
Hopefully this helps someone in the future.
Specifically:
logout-button.js
import React from "react";
import { useAuth0 } from "#auth0/auth0-react";
const LogoutButton = () => {
const { logout } = useAuth0();
localStorage.clear(); // this clears the old email address
return (
<button
className="btn btn-danger btn-block"
onClick={() =>{
logout({
returnTo: window.location.origin,
})
}
}
>
Log Out
</button>
);
};
export default LogoutButton;
app.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import { useAuth0 } from "#auth0/auth0-react";
import { NavBar, Footer, Loading } from "./components";
import { Home, Profile, ExternalApi } from "./views";
import ProtectedRoute from "./auth/protected-route";
import "./app.css";
const App = () => {
const { isLoading, logout, error} = useAuth0();
if (isLoading) {
return <Loading />;
}
if (typeof error !== 'undefined' && error.error === "unauthorized") { // The user does not exist. Completely log them out.
localStorage.clear();
logout({
returnTo: window.location.origin,
});
}
return (
<div id="app" className="d-flex flex-column h-100">
<NavBar />
<div className="container flex-grow-1">
<Switch>
<Route path="/" exact component={Home} />
<ProtectedRoute path="/profile" component={Profile} />
<ProtectedRoute path="/external-api" component={ExternalApi} />
</Switch>
</div>
<Footer />
</div>
);
};
export default App;
I am making a simple SPA where you need to login before you can access other pages. I can successfully login and store the login data (firstname, lastname, etc.) cause I plan to use the data again later in the other pages. The problem is whenever I refresh the page, it always empty the state in the context which cause me to return to the login page. I am referring link for my SPA.
Do I need to do this? I would be thankful if someone can point out what I should change / improve. Thank you.
Here is my code.
App.js
import React, { useState } from "react";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";
import { AuthContext } from "./context/auth";
import PrivateRoute from "./PrivateRoute";
import Login from "./pages/Login";
import Signup from "./pages/Signup";
import Home from "./pages/Home";
import Admin from "./pages/Admin";
function App() {
const [authTokens, setAuthTokens] = useState();
const setTokens = (data) => {
// console.log("DATA ",data);
localStorage.setItem("tokens", JSON.stringify(data));
setAuthTokens(data);
}
// console.log(authTokens);
return (
<AuthContext.Provider value={{ authTokens, setAuthTokens: setTokens }}>
<Router>
<div className="app">
<ul>
<li><Link to="/">Home Page</Link></li>
<li><Link to="/admin">Admin Page</Link></li>
</ul>
<Route exact path="/login" component={Login} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/" component={Home} />
<PrivateRoute exact path="/admin" component={Admin} />
</div>
</Router>
</AuthContext.Provider>
);
}
export default App;
Login.js
import React, { useState } from "react";
import axios from "axios";
import { Link, Redirect } from "react-router-dom";
import { useAuth } from "../context/auth";
import { Card, Form, Input, Button, Error } from "../components/AuthForm";
const Login = () => {
const [isLoggedIn, setLoggedIn] = useState(false);
const [isError, setIsError] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { setAuthTokens } = useAuth();
const handleLogin = () => {
axios
.post("LOGINLINK", {
email,
password,
})
.then((result) => {
if (result.status === 200) {
setAuthTokens(result.data);
setLoggedIn(true);
} else {
setIsError(true);
}
})
.catch((error) => {
setIsError(true);
});
};
if (isLoggedIn) {
return <Redirect to="/" />;
}
return (
<Card>
<Form>
<Input
type="email"
placeholder="Email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<Input
type="password"
placeholder="password"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
<Button onClick={handleLogin}>Login</Button>
</Form>
<Link to="/signup">Don't have an account?</Link>
{isError && (
<Error>The username or password provided were incorrect!</Error>
)}
</Card>
);
};
export default Login;
Auth.js
import { createContext, useContext } from "react";
export const AuthContext = createContext();
export function useAuth() {
console.log("CONTEXT", useContext(AuthContext));
return useContext(AuthContext);
}
In your App component you need to fetch the data from localStorage when initializing your state so it has some data to start with.
const localToken = JSON.parse(localStorage.getItem("tokens"));
const [authTokens, setAuthTokens] = useState(localToken);
If user has already authenticated it will be available in localStorage else it's going to be null.
I also had same problem but I solved liked this Don't use localStorage directly use your state and if it is undefined then only use localStorage. cause directly manipulating state with localStorage is in contrast with react internal state and effects re-render .
const getToken = () => {
JSON.parse(localStorage.getItem('yourtoken') || '')
}
const setToken = (token) => {
localStorage.setItem('key' , token)
}
const [authTokens, setAuthTokens] = useState(getToken());
const setTokens = (data) => {
// console.log("DATA ",data);
setToken(token);
setAuthTokens(data);
}
I have setup a login route in Express, which when used, it will set the global state of my application (using Context API), to include the users ID and a token, generated by JSONWebToken.
To be able to load todo items for the user, you need to have a valid token, which works when I'm sending it in the headers while doing the API request. The state is also being updated when doing this with Axios, but the problem is that I don't know how (or the best way for how) to forward to the protected route.
Here is my App.js, which includes the routes for my Welcome and Todo components. Inside of Welcome, there is a Login component, which updates the AppContext to contain the user ID and jsonwebtoken.
import React, { useContext } from 'react'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import { Switch } from 'react-router'
import TodoApp from './components/TodoApp/TodoApp'
import Welcome from './components/Welcome/Welcome'
import TodoProvider from './components/TodoApp/TodoContext'
import { AppContext } from './AppContext'
export default function App () {
const context = useContext(AppContext)
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
context.loggedIn ? <Component {...props} /> : <Redirect to="/" />
}
/>
)
return (
<Router>
<Switch>
<Route exact path="/" component={Welcome} />
<TodoProvider>
<PrivateRoute exact path="/todo" component={TodoApp} />
</TodoProvider>
</Switch>
</Router>
)
}
Notice the context.loggedIn property it checks for, which you can see how it's changed in the last code block of this post.
Here is my Login component which is inside of a simple Welcome component
import React, { useState, useContext } from 'react'
import { AppContext } from '../../../AppContext'
export default function Login (props) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const context = useContext(AppContext)
const handleSubmit = async e => {
e.preventDefault()
try {
// Method which logs in using the /api/login route, and returns users ID and token to the global state (context)
await context.handleLogin(email, password)
} catch {
throw Error('Login error')
}
}
return (
<form handleSubmit={handleSubmit}>
<div className="input-wrapper">
<label htmlFor="email" />
<input
type="text"
id="login_email"
placeholder="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
</div>
<div className="input-wrapper">
<label htmlFor="password" />
<input
type="password"
id="login_password"
placeholder="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</div>
<div className="input-wrapper">
<button
type="submit"
onClick={handleSubmit}
>
Log in
</button>
</div>
</form>
)
}
And finally, the method context.handleLogin which updates the state to contain the users ID and token. Taken from AppContext.js
handleLogin = (email, password) => {
axios
.post('http://localhost:4000/api/login/', {
email,
password
})
.then(response => {
this.setState({
loggedIn: response.httpStatus === 200,
userID: response.data.data.user._id,
token: response.data.data.token
})
})
.catch(err => {
this.setState({
httpStatus: err.response.status,
loginError: 'Incorrect email/password'
})
})
}
I'm new at React, so any help would be greatly appreciated. Thanks in advance!
I solved it by using withRouter() from react-router, and then pushing the history to the Private route.
Read more about it here:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md