I'm using reactjs as my development tool and mongoDB as my backend database.
I have my backend react code as following:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const { User, VerificationCode } = require("../models");
const { isLoggedIn, getLoggedInUserId, generateRefreshToken } = require("./middlewares");
const sendVerificationEMail = require("./bin/send_email").sendVerificationEmail;
require("dotenv").config();
const router = express.Router();
router.post("/register", async (req, res, next) => {
const { email, username, password, first_name, last_name } = req.body;
try {
// Check if the email is duplicating
let existingUser = await User.findOne({ where: { email } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "User already exists.",
});
}
existingUser = await User.findOne({ where: { username } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "Same nickname user exists.",
});
}
const hash = await bcrypt.hash(password, 12);
await User.create({
email,
username,
password: hash,
first_name,
last_name,
});
return res.status(200).json({
success: true,
message: "Signup successful.",
});
} catch (error) {
return res.json({
success: false,
message: "Signup failed.",
});
}
});
// Login
// Create token and return to user (httpOnly cookies)
router.post("/login", async (req, res, next) => {
const { email, password } = req.body;
// Make a inquiry of the user through email
try {
const user = await User.findOne({ where: { email }, raw: true });
if (!user) {
return res.status(401).json({
success: false,
message: "No member exists.",
});
}
// Check password
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
// If the password matches,create JWT payload
const payload = {
uid: user.id,
};
// JWT token create
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: req.app.get("jwt_expiration") });
// New refresh token and create expiration for it
let refresh_token = generateRefreshToken(req, user.id);
let refresh_token_maxage = new Date() + req.app.get("jwt_refresh_expiration");
// Browswer httpOnly cookie setting
res.cookie("access_token", token, {
// secure: true,
httpOnly: true,
});
res.cookie("refresh_token", refresh_token, {
// secure: true,
httpOnly: true,
});
// Save the account id as key and save in Redis server
req.client.set(
user.id,
JSON.stringify({
refresh_token: refresh_token,
expires: refresh_token_maxage,
}),
req.client.print
);
return res.json({
success: true,
uid: user.id,
message: "Login Successful",
});
} else {
return res.status(401).json({
success: false,
message: "Password's don't match.",
});
}
} catch (error) {
console.error(error);
res.status(401).json({
success: false,
message: "Login Error",
});
}
});
module.exports = router;
And I have my Login frontend code as following: (Login.js)
import React, { Component } from "react";
import login from "../picture/login.png";
import Form from "react-bootstrap/Form";
import axios from "axios";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Login</h2>
<hr />
<div class="row h-100 justify-content-center align-items-center">
<img src = {login}
width = '550'
height = '200'
alt='Login2'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Remember me" />
</Form.Group>
<button type="submit" className="btn btn-info btn-block">Submit</button>
<div className = "App-wrapper">
<p className="forgot-password text-right">
<a href="signup"to="/signup">
Sign Up | </a>
<a href="password"to="/pasword">
Find Password</a>
</p>
</div>
</form>
</div>
</div>
</div>
);
}
}
My Signup frontend code is:(Signup.js)
import React, { Component } from "react";
import Form from "react-bootstrap/Form";
import welcome from "../picture/welcome.png";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Sign Up</h2>
<hr />
<div class = "row h-100 justify-content-center align-items-center">
<img src = {welcome}
width = '550'
height = '200'
alt='signup'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>*Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
</Form.Group>
<Form.Group controlId="formBasicUsername">
<Form.Label>*Username</Form.Label>
<Form.Control placeholder="Enter username" />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>*Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicFirstname">
<Form.Label>*Firstname</Form.Label>
<Form.Control placeholder="Enter firstname" />
</Form.Group>
<Form.Group controlId="formBasicLastname">
<Form.Label>*Lastname</Form.Label>
<Form.Control type placeholder="Enter lastname" />
</Form.Group>
<Form.Group controlId="formBasicTelephone">
<Form.Label>Telephone</Form.Label>
<Form.Control type="number"placeholder="Enter telephone number"/>
</Form.Group>
<Form.Text className="text-muted">
Fields that are marked with asterisk(*) are compulsory.
</Form.Text>
<button type="submit" className="btn btn-info btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered? sign in?
</p>
</form>
</div>
</div>
</div>
);
}
}
I really don't know how to connect backend and frontend using axios. The login server url is localhost:8002/auth/login and for signup: localhost:8002/auth/signup
In your React component, you have to make a function that uses axios to call the backend, and then add that as a onClick handler to the submit button.
To make a request with axios you have to use the functions available on the axios module. In your case, this could look something like this:
function onSubmit() {
axios.post('localhost:8002/auth/login',
{username: username,
password: password });
}
Be aware that axios.post returns a promise, so you would have to await it/use .then to get the response from the backend. When you have the function, you can attach it to your login button like this:
<button type="submit" className="btn btn-info btn-block" onClick={onSubmit}>Submit</button>
EDIT: And the username and password values are of course the values that the user has entered via the input fields. You can store these in the state of the component.
Related
I am in the middle of creating error handlings using toast function for my react app signin and register pages, I was able to successfully create a toast function that when logging in with wrong email or password they should receive an error message.
however, I am trying to accomplish the same thing with a different error message when the user clicks on sign in without entering any information, but I can't get it to work, when I click on the login without entering anything it gives me the same error messgae as i set up when entering wrong credentials.
what am I missing?
please help me
from signin.js
import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
class Signin extends React.Component {
constructor(props) {
super(props);
this.state = {
signInEmail: "",
signInPassword: "",
};
}
showToast = () => {
toast.error("invalid username or password", {
position: "top-right",
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
};
showToast1 = () => {
toast.error("invalid username or password", {
position: "top-right",
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
};
onEmailChange = (event) => {
this.setState({ signInEmail: event.target.value });
};
onPasswordChange = (event) => {
this.setState({ signInPassword: event.target.value });
};
onSubmitSignIn = (event) => {
event.preventDefault();
let regex = /^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+#[A-Za-z0-9.-]+$/g;
const isEmailValid = this.state.signInEmail.match(regex);
const signInEmail = this.state.signInEmail
const signInPassword = this.state.signInPassword
if (!isEmailValid) {
return this.showToast();
} else if(!signInEmail || !signInPassword) {
return this.showToast1()
}
fetch("https://ancient-sea-46547.herokuapp.com/signin", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword,
}),
})
.then((response) => {
if (!response.ok) throw new Error("invalid");
return response.json();
})
.then((user) => {
if (user.id) {
this.props.loadUser(user);
this.props.onRouteChange("home");
}
})
.catch((error) => this.showToast(), this.showToast1);
};
render() {
const { onRouteChange } = this.props;
return (
<article className="br3 ba b--black-10 mv4 w-100 w-50-m w-25-l mw6 shadow-5 center">
<ToastContainer />
<main className="pa4 black-80">
<form className="measure">
<fieldset id="sign_up" className="ba b--transparent ph0 mh0">
<legend className="f1 fw6 ph0 mh0">Sign In</legend>
<div className="mt3">
<label className="db fw6 lh-copy f6" htmlFor="email-address">
Email
</label>
<input
className="pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="email"
name="email-address"
id="email-address"
onChange={this.onEmailChange}
/>
</div>
<div className="mv3">
<label className="db fw6 lh-copy f6" htmlFor="password">
Password
</label>
<input
className="b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-100"
type="password"
name="password"
id="password"
onChange={this.onPasswordChange}
/>
</div>
</fieldset>
<div className="">
<input
onClick={this.onSubmitSignIn}
className="b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib"
type="submit"
value="Sign in"
/>
</div>
<div className="lh-copy mt3">
<p
onClick={() => onRouteChange("register")}
className="f6 link dim black db pointer"
>
Register
</p>
</div>
</form>
</main>
</article>
);
}
}
export default Signin;
I'm building a form using React & Nodejs & MongoDB, where you can fill the form and upload a file with some other text inputs.
However, after i submit, i receive only text inputs in my database. The chosen file (desired to upload) doesn't appear at all in the database. I am expecting to get all the data form (the uploaded file and text inputed) in my database.
I tested my backend and it works correctly (it uploads all the inputs).
Ps: In browser, when i select a file (.pdf) to upload, the file input always shows no file chosen !
Console.dev : Error
{title: 'Miss', fname: 'zaezae', lname: 'zaeazee', email: 'zaea#mail.com', phoneNumber: '12345678', …}
coverLetter: "zaez e az ezae e zae aeae "
cv: ""
email: "zaea#mail.com"
fname: "zaezae"
lname: "zaeazee"
myFile: "C:\\fakepath\\test.pdf"
phoneNumber: "12345678"
title: "Miss"
Formulaire.jsx:29
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
at submit (Formulaire.jsx:29:1)
Backend:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
Axios.js:
import axios from 'axios'
export const Axios = axios.create({
baseURL: 'http://localhost:5000',
})
Apiroutes.js:
const form = "/api/form"
export const requests = {
formApi: {
store: form + '/store'
}
}
formservices.js:
import { Axios } from "../config/axios";
import { requests } from "../config/apiroutes";
export const FormService = {
store: (data) => {
Axios.post(requests.formApi.store, data)
.then(res => {
return res
})
.catch(err => {
return err
})
}
}
formController.js :
const form = require('../models/FormModel')
const store = (req, res, next) => {
let candidate = new form({
title: req.body.title,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
phoneNumber: req.body.phoneNumber,
coverLetter: req.body.coverLetter
})
if (req.file) {
candidate.cv = req.file.path
}
candidate.save()
.then(response => {
res.json({
success: true,
message: 'Candidate added successfully!',
data: candidate,
})
})
.catch(error => {
res.json({
success: false,
message: 'An error occured!',
error: error,
})
})
}
module.exports = {
store
}
Frontend:
Formulaire.jsx :
import React, { useState } from 'react'
import Divider from '#mui/material/Divider';
import './Formulaire.css'
import { titles } from '../../mock/titles'
import { FormService } from '../../services/formServices';
const Form = () => {
const [storedata, setstoredata] = useState({
title: '',
fname: '',
lname: '',
email: '',
phoneNumber: '',
cv: '',
coverLetter: ''
})
const handleChange = e => {
const { name, value } = e.target;
setstoredata(prevState => ({
...prevState,
[name]: value
}));
};
const submit = async () => {
console.log(storedata);
await FormService.store(storedata)
.then(res => {
console.log(res);
})
.catch(err => {
return err
})
}
return (
<div className='container'>
<div className='header'>
<div className='title'>
<a className='quizbutton' href="/quiz">Take a Test (Quiz)</a>
<h1>Apply for a Position :</h1>
</div>
</div>
<Divider style={{ maxWidth: '1000px', marginLeft: '250px' }} />
<div id="content">
<div id="formWrapper">
<form id="msform" method='post' action='/uploadFile' enctype="multipart/form-data">
<fieldset id="fieldset3">
<h2 class="fs-title">Please complete the form below for a position with us.</h2>
<h3 class="fs-subtitle">Reference 0001</h3>
{/* <div class="fs-error"></div> */}
<div class="wrapper">
<label for="title">Title :</label>
<select name="title" value={storedata.title} onChange={handleChange}>
<option hidden></option>
{
titles.map((c, i) => {
return (
<option key={i} value={c}>{c}</option>
)
})
}
</select>
<label for="fname">First Name<span>*</span> :</label>
<input type="text" name="fname" value={storedata.fname} onChange={handleChange} id="fname" placeholder="Please enter your first name" required />
<label for="lname">Last Name<span>*</span> :</label>
<input type="text" name="lname" value={storedata.lname} onChange={handleChange} id="lname" placeholder="Please enter your last name" required />
<label for="email">Email<span>*</span> :</label>
<input type="email" name="email" value={storedata.email} onChange={handleChange} id="email" placeholder="Please enter your email" required />
<label for="phoneNumber">Phone N° :</label>
<input type="number" name="phoneNumber" value={storedata.phoneNumber} onChange={handleChange} id="phoneNumber" placeholder="Phone number" />
<label for="CV">Upload CV <span>*</span>:</label>
<input type="file" name="myFile" id="cv" value={storedata.cv} onChange={handleChange} accept="application/msword, application/pdf" placeholder="Cover Letter" required />
<label for="coverLetter">Cover Letter :</label>
<textarea type="text" name="coverLetter" value={storedata.coverLetter} onChange={handleChange} id="coverLetter" placeholder="cover Letter" />
</div>
<br />
<input type="submit" name="submit" class="submit action-button" value="Submit" onClick={submit} />
</fieldset>
</form>
</div>
</div>
</div>
)
}
export default Form
I fixed my problem by changing name="myFile" id="cv" to name="cv" id="cv"
I'm building a portal where students from only 6 universities can participate so I need a way to limit the email address type to these 6 universities for example emails ending with #mit.edu
How do I implement this in React with the form validation set to characters and on clicking on of these formats from the dropdown the email is saved as such for example in the email input field if you write cassandra and select #mit.edu from the dropdown the email becomes cassandra#mit.edu
This is how my login component looks like
`
function LogIn() {
const [password, setPassword] = React.useState("");
const [email, setEmail] = React.useState("");
const [err, setErr] = React.useState(null);
const history = useHistory();
const handleSubmit = async (event, password, email) => {
event.preventDefault();
var myHeaders = new Headers();
myHeaders.set('Authorization', 'Basic ' + encode(email + ":" + password));
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
let response;
try {
response = await fetch (`${APIlink}/users`, requestOptions)
} catch (err) {
setErr("Incorrect Password. Please Retry.");
return;
}
const result = await response.text();
//console.log(result);
const json = JSON.parse(result);
//console.log(json);
//console.log(response);
if (response.status===200) {
setErr(null);
localStorage.setItem('isAuthenticated', true);
//context.updateToken(JSON.stringify(json.data));
history.push("/Projects");
} else {
setErr(json.error);
console.log(json.error);
}
};
return (
<div>
<Header />
<div className="register row justify-content-center align-items-center">
<div className = "w-50 p-3">
<h1>Log in</h1>
<Link to="/Register">or create a new account</Link>
<br></br>
<br></br>
<form>
<div className="input-group mb-3">
<input type="text" id="email"
value={email}
onChange= {(event) => {
setErr("");
setEmail(event.target.value); }}
className="form-control form-control-lg" placeholder=" institute email" aria-label="institute-email" aria-describedby="basic-addon2"/>
</div>
<small
style={{ color: "red", height: "10px", display: "inline-block" }}
>
{err == "user not found" ? "Account doesn't exist" : ""}
</small>
<div className="input-group mb-3">
<input type="text" id="password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
setErr("");
}}
className="form-control form-control-lg" placeholder="password" aria-label="password" aria-describedby="basic-addon2"/>
</div>
<small
style={{ color: "red", height: "10px", display: "inline-block" }}
>
{err == "incorrect password"
? "Incorrect Password"
: err == "Username and Password can't be empty"
? err
: ""}
</small>
<Submit
//loginState={loginState}
onClick={(event) => {
event.preventDefault();
if (email != "" && password != "") {
handleSubmit(event, password, email);
} else {
setErr("Username and Password can't be empty");
}
}}
>
{" "}
Log In
</Submit>
</form>
</div>
</div>
</div>
)
}
export default LogIn;
`
You can use regex to validate email. Add this validateEmail function right after clicking on submit and pass the email that you want to validate, then proceed further only if it returns true (it will return true if it matches the pattern).
function validateEmail(email)
{
var regex = /^[^\s#]+#mit\.edu$/;
var result = regex.test(email);
if(result == true){
//Proceed further
}
else{
console.log("Enter correct email address!")
}
}
According to this regex, it will return true only if there is exact '#mit.edu' right after any string. Like:-
'anystring#mit.edu' //Returns true
'anystring#mit.com' //Returns false
'anystring#mit.edu.com' //Returns false
You can do this similarly with other domains just replace mit.edu with any other domain or if the domain has more length then simply add '\.domain' for example: -
var regex = /^[^\s#]+#mit\.edu\.com$/;
This will return true if email is 'anystring#mit.edu.com'.
EDIT: A slight correction. Remove '+' after mit and edu, as it returns true on these conditions: -
anystring#mitt.edu
anystring#mit.eduu
Check the regex above now, it should work perfectly.
I am currently working on a VueJs3 Project. I already coded a login system, which works perfectly fine. I now want to have a div on the homepage, that tells the user with which account they are logged in.
"You are logged in as:" + username
I therefore, have to send the username from the login component to the home component. Can someone help me out here? I have tried out a lot of ways but none of them seem to work.
Btw. the components are all saved in the components folder
Here is my code:
home.vue
<div class="home">
<h1>You are logged in as: {{currentusername}}</h1>
<Maschinen/>
</div>
</template>
<script>
import Maschinen from '#/components/Maschinen.vue'
import axios from 'axios'
export default {
name: 'Home',
components: {
Maschinen
},
data() {
return {
currentusername: null,
}
},
async created() {
const response = await axios.get('http://localhost:8080/user/hetwinuser', {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
});
this.currentusername= (response.data.username);
}
}
</script>
login.vue:
<template>
<form #submit.prevent="handleSubmit">
<h1>Login</h1>
<!--username + pw input for login-->
<div class="form-group">
<label id="username">Username:</label>
<input id="usernameinput" type="text" class="form-control" v-model="username" placeholder="Username">
</div>
<div>
<label id="password">Password:</label>
<input id="passwordinput" type="password" class="form-control" v-model="password" placeholder="Password">
</div>
<!--enter buttons-->
<button class="enter">Enter</button>
<router-link to="/register" id="goToRegister" tag="button">Register</router-link>
</form>
</template>
<script>
import axios from 'axios';
export default {
name: "Login",
data: () => {
return {
username: '',
password: ''
}
},
methods: {
async handleSubmit() {//executed when enter button is pressed
const data = {
username: this.username,
password: this.password
};
axios.post('http://localhost:8080/authenticate', data) //post the username + pw and will receive the token in exchange
.then(
res => {
localStorage.setItem('token', res.data.jwt);
localStorage.setItem('currentusername', this.username);
//console.log(localStorage.getItem('token'));
}
).catch(
err => {
console.log(err)
}
);
}
},
}
</script>```
username and password
Define it under store -> state.js. Then where you want it
Use it as "this.$store.state.username"
I really need help cause I'm totally new to reactjs. How can I maintain the logged-in user throughout the page? like a session. the code shows the data called when I logged in. I'm really lost here in react.
When the credentials are true, here's the result
{userId: 1, firstname: "Jeff", middlename: null, lastname: "Geli", positionId: 1, …}
userId: 1
firstname: "Jeff"
middlename: null
lastname: "Geli"
positionId: 1
token: "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJMb2dnZWRVc2VyIjoie1wiVXNlcklkXCI6MSxcIkZpcnN0bmFtZVwiOlwiSmVmZlwiLFwiTWlkZGxlbmFtZVwiOm51bGwsXCJMYXN0bmFtZVwiOlwiR2VsaVwiLFwiUG9zaXRpb25JZFwiOjEsXCJUb2tlblwiOm51bGx9IiwiZXhwIjoxNTc5NzU5MzI5LCJpc3MiOiJzbWVzay5pbiIsImF1ZCI6InJlYWRlcnMifQ.xXPW0ijBdULuMBfhFGyL1qF1bA--FzG64jEJVMQZWY8"
__proto__: Object
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import { PageSettings } from './../../config/page-settings.js';
import bg from '../../assets/login-bg-17.jpg';
import axios from "axios";
class LoginV2 extends React.Component {
static contextType = PageSettings;
constructor(props) {
super(props);
//credentials for login
this.state = {
username: '',
password: '',
};
this.handleSuccess = this.handleSuccess.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.context.handleSetPageSidebar(false);
this.context.handleSetPageHeader(false);
}
componentWillUnmount() {
this.context.handleSetPageSidebar(true);
this.context.handleSetPageHeader(true);
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
};
handleSuccess(data) {
alert("Logged IN");
this.props.history.push('dashboard/v2');
}
//When submit button is clicked, fetch API
async handleSubmit(event) {
event.preventDefault();
//fetch API, method POST
const getCred = await fetch('/api/login', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'ApiKey': "Secret"
},
method: "POST",
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
});
const data = await getCred.json();
if (getCred.status == 400) {
alert(data);
} else {
this.handleSuccess(getCred);
}
console.log(data);
}
render() {
return (
<React.Fragment>
<div className="login-cover">
<div className="login-cover-image" style={{backgroundImage:'url('+ bg +')'}} >
</div>
<div className="login-cover-bg"></div>
</div>
<div className="login login-v2">
<div className="login-header">
<div className="brand">
<span className="logo"></span> <b>Tek</b> Teach
<small>Leraning Management System</small>
</div>
<div className="icon">
<i className="fa fa-lock"></i>
</div>
</div>
<div className="login-content">
<form className="margin-bottom-0" onSubmit={this.handleSubmit}>
<div className="form-group m-b-20">
<input type="text" className="form-control form-control-lg" placeholder="Username" name="username" value={this.state.username} onChange={this.handleChange} required />
</div>
<div className="form-group m-b-20">
<input type="password" className="form-control form-control-lg" placeholder="Password" name="password" value={this.state.password} onChange={this.handleChange} required />
</div>
<div className="login-buttons">
<button type="submit" className="btn btn-success btn-block btn-lg" onClick={this.login}>Sign me in</button>
</div>
</form>
</div>
</div>
</React.Fragment>
)
}
}
export default withRouter(LoginV2);
You could use sessionStorage or localStorage to store the token and then check for it, if it is set then keep user logged in otherwise logout user.
set the session once user logged in
if (token) {
localStorage.setItem('session', JSON.stringify(token));
}
To check if the user is logged in
let user = localStorage.getItem('session');
if (user) {
console.log('Valid session');
} else {
console.log('Not valid session');
}
On logut clear the value
let user = localStorage.getItem('session');
if (user) {
localStorage.removeItem();
}
Adding the logic in the provided code
async handleSubmit(event) {
// .... Other code
const data = await getCred.json();
if (data.status == 400) {
alert(data);
} else {
this.handleSuccess(data);
}
console.log(data);
}
//Set your token in handleSuccess method
handleSuccess(data) {
alert("Logged IN");
if (data.token) {
localStorage.setItem('session', JSON.stringify(data.token));
}
this.props.history.push('dashboard/v2');
}