article

Friday, April 14, 2023

React and Python Flask Login Register

React and Python Flask Login Register

Python Flask 

https://flask.palletsprojects.com/en/2.2.x/installation/
 
Create an environment
C:\flask_dev>py -3 -m venv venv

Activate the environment
C:\flask_dev>venv\Scripts\activate

Install Flask
venv C:\flask_dev>pip install Flask
C:\flask_dev\flaskreact\app.py
Install requirements
Flask-Bcrypt
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.
https://pypi.org/project/Flask-Bcrypt/

(venv) PS C:\flask_dev\flaskreact>pip install Flask-Bcrypt

Flask-SQLAlchemy
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application.
https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/

(venv) PS C:\flask_dev\flaskreact>pip install -U Flask-SQLAlchemy
C:\flask_dev\flaskreact\app.py

C:\flask_dev\flaskreact\app.py
 
#C:\flask_dev\flaskreact\app.py
from flask import Flask, request, jsonify, session
from flask_bcrypt import Bcrypt #pip install Flask-Bcrypt = https://pypi.org/project/Flask-Bcrypt/
from flask_cors import CORS, cross_origin #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
from models import db, User

app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flaskdb.db'

SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
 
bcrypt = Bcrypt(app) 
CORS(app, supports_credentials=True)
db.init_app(app)
 
with app.app_context():
    db.create_all()

@app.route("/")
def hello_world():
    return "Hello, World!"

@app.route("/signup", methods=["POST"])
def signup():
    email = request.json["email"]
    password = request.json["password"]

    user_exists = User.query.filter_by(email=email).first() is not None

    if user_exists:
        return jsonify({"error": "Email already exists"}), 409
    
    hashed_password = bcrypt.generate_password_hash(password)
    new_user = User(email=email, password=hashed_password)
    db.session.add(new_user)
    db.session.commit()

    session["user_id"] = new_user.id

    return jsonify({
        "id": new_user.id,
        "email": new_user.email
    })

@app.route("/login", methods=["POST"])
def login_user():
    email = request.json["email"]
    password = request.json["password"]
 
    user = User.query.filter_by(email=email).first()
 
    if user is None:
        return jsonify({"error": "Unauthorized Access"}), 401
 
    if not bcrypt.check_password_hash(user.password, password):
        return jsonify({"error": "Unauthorized"}), 401
     
    session["user_id"] = user.id
 
    return jsonify({
        "id": user.id,
        "email": user.email
    })

if __name__ == "__main__":
    app.run(debug=True)
C:\flask_dev\flaskreact\models.py
 
#C:\flask_dev\flaskreact\models.py
from flask_sqlalchemy import SQLAlchemy
from uuid import uuid4

db = SQLAlchemy()

def get_uuid():
    return uuid4().hex

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.String(11), primary_key=True, unique=True, default=get_uuid)
    email = db.Column(db.String(150), unique=True)
    password = db.Column(db.Text, nullable=False)
Postman
Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.
https://www.postman.com/

run (venv) C:\flask_dev\flaskreact>flask run

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start
C:\react-js\myreactdev\src\App.js
//C:\react-js\myreactdev\src\App.js
import React, { } from 'react';
import './App.css';
 
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
 
import LandingPage from "./pages/LandingPage";
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'

function App() {
  return (
    <div className="vh-100 gradient-custom">
    <div className="container">
      <h1 className="page-header text-center">React and Python Flask Login Register</h1>
  
      <BrowserRouter>
        <Routes>
            <Route path="/" element={<LandingPage />} />
            <Route path="/login" element={<LoginPage />} />
            <Route path="/register" element={<RegisterPage />} />
        </Routes>
      </BrowserRouter>
    </div>
    </div>
  );
}
  
export default App;
Install React Router Dom
https://www.npmjs.com/package/react-router-dom
C:\react-js\myreactdev>npm i react-router-dom --save
Install Axios
https://www.npmjs.com/package/axios
C:\react-js\myreactdev>npm install axios --save

C:\react-js\myreactdev\src\pages\LandingPage.js
//C:\react-js\myreactdev\src\pages\LandingPage.js
import React, { } from "react";

import {Link} from 'react-router-dom';

export default function LandingPage(){

  return (
    <div>
        <div className="container h-100">
            <div className="row h-100">
				<div className="col-12">
					<h1>Welcome to this React Application</h1>
					<p><Link to="/login" className="btn btn-success">Login</Link> | <Link to="/register" className="btn btn-success">register</Link> </p>
				</div>
            </div>
        </div>
    </div>
  );
}
C:\react-js\myreactdev\src\pages\LoginPage.js
//C:\react-js\myreactdev\src\pages\LoginPage.js
import React, { useState } from "react";
import axios from 'axios';
import {useNavigate} from "react-router-dom";

export default function LoginPage(){

    const [email,setEmail] = useState('');
    const [password,setPassword] = useState('');
  
	const navigate = useNavigate();
	
	const logInUser = () => {
        if(email.length === 0){
          alert("Email has left Blank!");
        }
        else if(password.length === 0){
          alert("password has left Blank!");
        }
        else{
            axios.post('http://127.0.0.1:5000/login', {
                email: email,
                password: password
            })
            .then(function (response) {
                console.log(response);
                //console.log(response.data);
				navigate("/");
            })
            .catch(function (error) {
                console.log(error, 'error');
				if (error.response.status === 401) {
					alert("Invalid credentials");
				}
            });
        }
    }

	let imgs = [
	  'https://as1.ftcdn.net/v2/jpg/03/39/70/90/1000_F_339709048_ZITR4wrVsOXCKdjHncdtabSNWpIhiaR7.jpg',
	];
	
  return (
    <div>
        <div className="container h-100">
		  <div className="container-fluid h-custom">
			<div className="row d-flex justify-content-center align-items-center h-100">
			  <div className="col-md-9 col-lg-6 col-xl-5">
				<img src={imgs[0]} className="img-fluid"/>
			  </div>
			  <div className="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
				<form>
				  <div className="d-flex flex-row align-items-center justify-content-center justify-content-lg-start">
					<p className="lead fw-normal mb-0 me-3">Log Into Your Account</p>
				  </div>

				  <div className="form-outline mb-4">
					<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} id="form3Example3" className="form-control form-control-lg" placeholder="Enter a valid email address" />
					<label className="form-label" for="form3Example3">Email address</label>
				  </div>

			
				  <div className="form-outline mb-3">
					<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} id="form3Example4" className="form-control form-control-lg" placeholder="Enter password" />
					<label className="form-label" for="form3Example4">Password</label>
				  </div>

				  <div className="d-flex justify-content-between align-items-center">
					<div className="form-check mb-0">
					  <input className="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
					  <label className="form-check-label" for="form2Example3">
						Remember me
					  </label>
					</div>
					<a href="#!" className="text-body">Forgot password?</a>
				  </div>

				  <div className="text-center text-lg-start mt-4 pt-2">
					<button type="button" className="btn btn-primary btn-lg" onClick={logInUser} >Login</button>
					<p className="small fw-bold mt-2 pt-1 mb-0">Don't have an account? <a href="/register" className="link-danger">Register</a></p>
				  </div>

				</form>
			  </div>
			</div>
		  </div>
		</div>
    </div>
  );
}
C:\react-js\myreactdev\src\pages\RegisterPage.js
//C:\react-js\myreactdev\src\pages\RegisterPage.js
import React, { useState } from "react";
import axios from 'axios';
import {useNavigate} from "react-router-dom";

export default function RegisterPage(){

    const [email,setEmail] = useState('');
    const [password,setPassword] = useState('');
  
	const navigate = useNavigate();
	
	const registerUser = () => {
        axios.post('http://127.0.0.1:5000/signup', {
            email: email,
            password: password
        })
        .then(function (response) {
             console.log(response);
			navigate("/");
        })
        .catch(function (error) {
            console.log(error, 'error');
			if (error.response.status === 401) {
				alert("Invalid credentials");
			}
        });
	};
	
	let imgs = [
	  'https://as2.ftcdn.net/v2/jpg/03/39/70/91/1000_F_339709132_H9HSSTtTmayePcbARkTSB2qoZTubJ6bR.jpg',
	];
	
  return (
    <div>
        <div className="container h-100">
		  <div className="container-fluid h-custom">
			<div className="row d-flex justify-content-center align-items-center h-100">
			  <div className="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
				<form>
				  <div className="d-flex flex-row align-items-center justify-content-center justify-content-lg-start">
					<p className="lead fw-normal mb-0 me-3">Create Your Account</p>
				  </div>

				  <div className="form-outline mb-4">
					<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} id="form3Example3" className="form-control form-control-lg" placeholder="Enter a valid email address" />
					<label className="form-label" for="form3Example3">Email address</label>
				  </div>

			
				  <div className="form-outline mb-3">
					<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} id="form3Example4" className="form-control form-control-lg" placeholder="Enter password" />
					<label className="form-label" for="form3Example4">Password</label>
				  </div>

				  <div className="d-flex justify-content-between align-items-center">
					<div className="form-check mb-0">
					  <input className="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
					  <label className="form-check-label" for="form2Example3">
						Remember me
					  </label>
					</div>
					<a href="#!" className="text-body">Forgot password?</a>
				  </div>

				  <div className="text-center text-lg-start mt-4 pt-2">
					<button type="button" className="btn btn-primary btn-lg" onClick={() => registerUser()} >Sign Up</button>
					<p className="small fw-bold mt-2 pt-1 mb-0">Login to your account <a href="/login" className="link-danger">Login</a></p>
				  </div>

				</form>
			  </div>
			  <div className="col-md-9 col-lg-6 col-xl-5">
				<img src={imgs[0]} className="img-fluid"/>
			  </div>
			</div>
		  </div>
		</div>
    </div>
  );
}
react-js\myreactdev\src\App.css
body {
  margin: 0;
  background-color: #ffffff;
}

.h-100 {
	margin-top:100px;
}	
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

Related Post