├── server ├── .env ├── requirements.txt ├── models.py ├── config.py └── app.py ├── client ├── src │ ├── react-app-env.d.ts │ ├── types.ts │ ├── httpClient.ts │ ├── pages │ │ ├── NotFound.tsx │ │ ├── LandingPage.tsx │ │ ├── RegisterPage.tsx │ │ └── LoginPage.tsx │ ├── index.tsx │ ├── index.css │ └── Router.tsx ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── tsconfig.json ├── package.json └── README.md ├── README.md ├── .gitignore └── LICENSE /server/.env: -------------------------------------------------------------------------------- 1 | SECRET_KEY=put_your_secret_key_here -------------------------------------------------------------------------------- /client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /client/src/types.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | id: string; 3 | email: string; 4 | } 5 | -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Flask React Session Authentication 2 | 3 | Video: https://www.youtube.com/watch?v=sBw0O5YTT4Q 4 | -------------------------------------------------------------------------------- /server/requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-sqlalchemy 3 | flask-bcrypt 4 | python-dotenv 5 | flask-session 6 | redis 7 | flask-cors -------------------------------------------------------------------------------- /client/src/httpClient.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | 3 | export default axios.create({ 4 | withCredentials: true, 5 | }); 6 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahnaf-zamil/flask-react-session-authenticaton-tutorial/HEAD/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahnaf-zamil/flask-react-session-authenticaton-tutorial/HEAD/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ahnaf-zamil/flask-react-session-authenticaton-tutorial/HEAD/client/public/logo512.png -------------------------------------------------------------------------------- /client/src/pages/NotFound.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NotFound: React.FC = () => { 4 | return ( 5 |
6 |

404 not found

7 |
8 | ); 9 | }; 10 | 11 | export default NotFound; 12 | -------------------------------------------------------------------------------- /client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import "./index.css"; 4 | import Router from "./Router"; 5 | 6 | ReactDOM.render( 7 | 8 | 9 | , 10 | document.getElementById("root") 11 | ); 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | node_modules 3 | .pnp 4 | .pnp.js 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | 23 | 24 | venv/ 25 | db.sqlite 26 | __pycache__/ 27 | -------------------------------------------------------------------------------- /server/models.py: -------------------------------------------------------------------------------- 1 | from flask_sqlalchemy import SQLAlchemy 2 | from uuid import uuid4 3 | 4 | db = SQLAlchemy() 5 | 6 | def get_uuid(): 7 | return uuid4().hex 8 | 9 | class User(db.Model): 10 | __tablename__ = "users" 11 | id = db.Column(db.String(32), primary_key=True, unique=True, default=get_uuid) 12 | email = db.Column(db.String(345), unique=True) 13 | password = db.Column(db.Text, nullable=False) 14 | -------------------------------------------------------------------------------- /server/config.py: -------------------------------------------------------------------------------- 1 | from dotenv import load_dotenv 2 | import os 3 | import redis 4 | 5 | load_dotenv() 6 | 7 | class ApplicationConfig: 8 | SECRET_KEY = os.environ["SECRET_KEY"] 9 | 10 | SQLALCHEMY_TRACK_MODIFICATIONS = False 11 | SQLALCHEMY_ECHO = True 12 | SQLALCHEMY_DATABASE_URI = r"sqlite:///./db.sqlite" 13 | 14 | SESSION_TYPE = "redis" 15 | SESSION_PERMANENT = False 16 | SESSION_USE_SIGNER = True 17 | SESSION_REDIS = redis.from_url("redis://127.0.0.1:6379") -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | 15 | button { 16 | margin: 5px; 17 | padding: 5px; 18 | } 19 | 20 | label { 21 | font-size: 20px; 22 | } 23 | 24 | input { 25 | font-size: 18px; 26 | margin-left: 5px; 27 | } 28 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /client/src/Router.tsx: -------------------------------------------------------------------------------- 1 | import { BrowserRouter, Switch, Route } from "react-router-dom"; 2 | import LandingPage from "./pages/LandingPage"; 3 | import LoginPage from "./pages/LoginPage"; 4 | import NotFound from "./pages/NotFound"; 5 | import RegisterPage from "./pages/RegisterPage"; 6 | 7 | const Router = () => { 8 | return ( 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ); 18 | }; 19 | 20 | export default Router; 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 DevGuyAhnaf 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.11.4", 7 | "@testing-library/react": "^11.1.0", 8 | "@testing-library/user-event": "^12.1.10", 9 | "@types/jest": "^26.0.15", 10 | "@types/node": "^12.0.0", 11 | "@types/react": "^17.0.0", 12 | "@types/react-dom": "^17.0.0", 13 | "axios": "^0.22.0", 14 | "react": "^17.0.2", 15 | "react-dom": "^17.0.2", 16 | "react-router-dom": "^5.3.0", 17 | "react-scripts": "4.0.3", 18 | "typescript": "^4.1.2", 19 | "web-vitals": "^1.0.1" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "build": "react-scripts build", 24 | "test": "react-scripts test", 25 | "eject": "react-scripts eject" 26 | }, 27 | "eslintConfig": { 28 | "extends": [ 29 | "react-app", 30 | "react-app/jest" 31 | ] 32 | }, 33 | "browserslist": { 34 | "production": [ 35 | ">0.2%", 36 | "not dead", 37 | "not op_mini all" 38 | ], 39 | "development": [ 40 | "last 1 chrome version", 41 | "last 1 firefox version", 42 | "last 1 safari version" 43 | ] 44 | }, 45 | "devDependencies": { 46 | "@types/react-router-dom": "^5.3.0" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /client/src/pages/LandingPage.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import httpClient from "../httpClient"; 3 | import { User } from "../types"; 4 | 5 | const LandingPage: React.FC = () => { 6 | const [user, setUser] = useState(null); 7 | 8 | const logoutUser = async () => { 9 | await httpClient.post("//localhost:5000/logout"); 10 | window.location.href = "/"; 11 | }; 12 | 13 | useEffect(() => { 14 | (async () => { 15 | try { 16 | const resp = await httpClient.get("//localhost:5000/@me"); 17 | setUser(resp.data); 18 | } catch (error) { 19 | console.log("Not authenticated"); 20 | } 21 | })(); 22 | }, []); 23 | 24 | return ( 25 |
26 |

Welcome to this React Application

27 | {user != null ? ( 28 |
29 |

Logged in

30 |

ID: {user.id}

31 |

Email: {user.email}

32 | 33 | 34 |
35 | ) : ( 36 |
37 |

You are not logged in

38 |
39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |
47 | )} 48 |
49 | ); 50 | }; 51 | 52 | export default LandingPage; 53 | -------------------------------------------------------------------------------- /client/src/pages/RegisterPage.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import httpClient from "../httpClient"; 3 | 4 | const RegisterPage: React.FC = () => { 5 | const [email, setEmail] = useState(""); 6 | const [password, setPassword] = useState(""); 7 | 8 | const registerUser = async () => { 9 | try { 10 | const resp = await httpClient.post("//localhost:5000/register", { 11 | email, 12 | password, 13 | }); 14 | 15 | window.location.href = "/"; 16 | } catch (error: any) { 17 | if (error.response.status === 401) { 18 | alert("Invalid credentials"); 19 | } 20 | } 21 | }; 22 | 23 | return ( 24 |
25 |

Create an account

26 |
27 |
28 | 29 | setEmail(e.target.value)} 33 | id="" 34 | /> 35 |
36 |
37 | 38 | setPassword(e.target.value)} 42 | id="" 43 | /> 44 |
45 | 48 |
49 |
50 | ); 51 | }; 52 | 53 | export default RegisterPage; 54 | -------------------------------------------------------------------------------- /client/src/pages/LoginPage.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import httpClient from "../httpClient"; 3 | 4 | const LoginPage: React.FC = () => { 5 | const [email, setEmail] = useState(""); 6 | const [password, setPassword] = useState(""); 7 | 8 | const logInUser = async () => { 9 | console.log(email, password); 10 | 11 | try { 12 | const resp = await httpClient.post("//localhost:5000/login", { 13 | email, 14 | password, 15 | }); 16 | 17 | window.location.href = "/"; 18 | } catch (error: any) { 19 | if (error.response.status === 401) { 20 | alert("Invalid credentials"); 21 | } 22 | } 23 | }; 24 | 25 | return ( 26 |
27 |

Log Into Your Account

28 |
29 |
30 | 31 | setEmail(e.target.value)} 35 | id="" 36 | /> 37 |
38 |
39 | 40 | setPassword(e.target.value)} 44 | id="" 45 | /> 46 |
47 | 50 |
51 |
52 | ); 53 | }; 54 | 55 | export default LoginPage; 56 | -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `yarn start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `yarn test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `yarn build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `yarn eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /server/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, jsonify, session 2 | from flask_bcrypt import Bcrypt 3 | from flask_cors import CORS, cross_origin 4 | from flask_session import Session 5 | from config import ApplicationConfig 6 | from models import db, User 7 | 8 | app = Flask(__name__) 9 | app.config.from_object(ApplicationConfig) 10 | 11 | bcrypt = Bcrypt(app) 12 | CORS(app, supports_credentials=True) 13 | server_session = Session(app) 14 | db.init_app(app) 15 | 16 | with app.app_context(): 17 | db.create_all() 18 | 19 | @app.route("/@me") 20 | def get_current_user(): 21 | user_id = session.get("user_id") 22 | 23 | if not user_id: 24 | return jsonify({"error": "Unauthorized"}), 401 25 | 26 | user = User.query.filter_by(id=user_id).first() 27 | return jsonify({ 28 | "id": user.id, 29 | "email": user.email 30 | }) 31 | 32 | @app.route("/register", methods=["POST"]) 33 | def register_user(): 34 | email = request.json["email"] 35 | password = request.json["password"] 36 | 37 | user_exists = User.query.filter_by(email=email).first() is not None 38 | 39 | if user_exists: 40 | return jsonify({"error": "User already exists"}), 409 41 | 42 | hashed_password = bcrypt.generate_password_hash(password) 43 | new_user = User(email=email, password=hashed_password) 44 | db.session.add(new_user) 45 | db.session.commit() 46 | 47 | session["user_id"] = new_user.id 48 | 49 | return jsonify({ 50 | "id": new_user.id, 51 | "email": new_user.email 52 | }) 53 | 54 | @app.route("/login", methods=["POST"]) 55 | def login_user(): 56 | email = request.json["email"] 57 | password = request.json["password"] 58 | 59 | user = User.query.filter_by(email=email).first() 60 | 61 | if user is None: 62 | return jsonify({"error": "Unauthorized"}), 401 63 | 64 | if not bcrypt.check_password_hash(user.password, password): 65 | return jsonify({"error": "Unauthorized"}), 401 66 | 67 | session["user_id"] = user.id 68 | 69 | return jsonify({ 70 | "id": user.id, 71 | "email": user.email 72 | }) 73 | 74 | @app.route("/logout", methods=["POST"]) 75 | def logout_user(): 76 | session.pop("user_id") 77 | return "200" 78 | 79 | if __name__ == "__main__": 80 | app.run(debug=True) --------------------------------------------------------------------------------