├── .gitignore ├── README.md ├── client ├── .env.example ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── descope.jpeg │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── components │ ├── Dashboard.js │ ├── Home.js │ ├── Login.js │ └── Profile.js │ ├── index.css │ ├── index.js │ ├── reportWebVitals.js │ └── setupTests.js ├── package-lock.json ├── package.json ├── renovate.json └── server ├── .env.example ├── Makefile ├── README.md ├── pyproject.toml ├── server ├── __init__.py └── app.py └── tests └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | /server/poetry.lock 6 | 7 | .DS_Store 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # poetry 101 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 102 | # This is especially recommended for binary packages to ensure reproducibility, and is more 103 | # commonly ignored for libraries. 104 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 105 | #poetry.lock 106 | 107 | # pdm 108 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 109 | #pdm.lock 110 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 111 | # in version control. 112 | # https://pdm.fming.dev/#use-with-ide 113 | .pdm.toml 114 | 115 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 116 | __pypackages__/ 117 | 118 | # Celery stuff 119 | celerybeat-schedule 120 | celerybeat.pid 121 | 122 | # SageMath parsed files 123 | *.sage.py 124 | 125 | # Environments 126 | .env 127 | .venv 128 | env/ 129 | venv/ 130 | ENV/ 131 | env.bak/ 132 | venv.bak/ 133 | 134 | # Spyder project settings 135 | .spyderproject 136 | .spyproject 137 | 138 | # Rope project settings 139 | .ropeproject 140 | 141 | # mkdocs documentation 142 | /site 143 | 144 | # mypy 145 | .mypy_cache/ 146 | .dmypy.json 147 | dmypy.json 148 | 149 | # Pyre type checker 150 | .pyre/ 151 | 152 | # pytype static type analyzer 153 | .pytype/ 154 | 155 | # Cython debug symbols 156 | cython_debug/ 157 | 158 | # PyCharm 159 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 160 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 161 | # and can be added to the global gitignore or merged into this file. For a more nuclear 162 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 163 | #.idea/ 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![react-flask](https://github.com/descope-sample-apps/flask-react-sample-app/assets/59460685/d38a6e4c-56ff-49f5-a0f1-fdf86bd4109d) 2 | 3 | # Flask-React Sample app with Descope Auth 4 | 5 | Add Descope's Python SDK to add authentication to a Flask + React.js app. The project will feature multiple pages, protected routes, and logout functionality. 6 | 7 | ## ⚙️ Setup 8 | 9 | 1. Clone the repository: 10 | 11 | ``` 12 | git clone https://github.com/descope-sample-apps/flask-react-sample-app.git 13 | ``` 14 | 15 | 2. Install dependencies: 16 | 17 | ``` 18 | npm run setup 19 | ``` 20 | 21 | 3. Client Setup 22 | 23 | Create a ```.env``` file in the root directory of the `client` folder and add your Descope [Project ID](https://app.descope.com/settings/project) in the file: 24 | 25 | ``` 26 | REACT_APP_PROJECT_ID="YOUR_DESCOPE_PROJECT_ID" 27 | ``` 28 | 29 | > **NOTE**: If you're running your flask server on a different port than 5000, change the ```"proxy":"http://127.0.0.1:5000/"``` value to wherever your server is hosted. You can edit the proxy value in your client package.json file. 30 | 31 | 4. Server Setup 32 | 33 | Since this app also showcases roles, it will require you to set them up in the Descope Console. 34 | 35 | - Create two different [roles]((https://app.descope.com/authorization)) called "teacher" and "student"
36 | - Create a ```.env``` file in the server folder and add your project id in the file: 37 | ``` 38 | PROJECT_ID="YOUR_DESCOPE_PROJECT_ID" 39 | ``` 40 | 41 | ## 🔮 Running the Application 42 | 43 | To run the server: 44 | 45 | ``` 46 | npm run server 47 | ``` 48 | 49 | To run the client: 50 | 51 | ``` 52 | npm run client 53 | ``` 54 | 55 | ## 📁 Folder Structure 56 | 57 | - Server: the server folder contains the flask app and server that will handle session validation 58 | - `app.py`: our main flask app 59 | - `requirements.txt`: a txt file with a list of our dependencies 60 | - Client: our react app 61 | 62 | ## ⚠️ Issue Reporting 63 | 64 | For any issues or suggestions, feel free to open an issue in the GitHub repository. 65 | 66 | ## 📜 License 67 | 68 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /client/.env.example: -------------------------------------------------------------------------------- 1 | REACT_APP_PROJECT_ID="YOUR_DESCOPE_PROJECT_ID" -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /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 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm 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 | ### `npm run 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 | ### `npm run 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 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "descope-flask", 3 | "version": "0.1.0", 4 | "private": true, 5 | "proxy": "http://127.0.0.1:5000/", 6 | "dependencies": { 7 | "@descope/react-sdk": "^1.0.3", 8 | "@testing-library/jest-dom": "^5.16.5", 9 | "@testing-library/react": "^13.4.0", 10 | "@testing-library/user-event": "^13.5.0", 11 | "react": "^18.2.0", 12 | "react-dom": "^18.2.0", 13 | "react-router-dom": "^6.11.2", 14 | "react-scripts": "5.0.1", 15 | "web-vitals": "^2.1.4" 16 | }, 17 | "scripts": { 18 | "start": "react-scripts start", 19 | "build": "react-scripts build", 20 | "test": "react-scripts test", 21 | "eject": "react-scripts eject" 22 | }, 23 | "eslintConfig": { 24 | "extends": [ 25 | "react-app", 26 | "react-app/jest" 27 | ] 28 | }, 29 | "browserslist": { 30 | "production": [ 31 | ">0.2%", 32 | "not dead", 33 | "not op_mini all" 34 | ], 35 | "development": [ 36 | "last 1 chrome version", 37 | "last 1 firefox version", 38 | "last 1 safari version" 39 | ] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /client/public/descope.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/client/public/descope.jpeg -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | Descope Flask Demo 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/client/public/logo512.png -------------------------------------------------------------------------------- /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/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Golos+Text:wght@500&display=swap'); 2 | 3 | 4 | .App { 5 | text-align: center; 6 | font-family: 'Golos Text', sans-serif; 7 | } 8 | .page { 9 | display: flex; 10 | flex-direction: column; 11 | align-items: center; 12 | justify-content: center; 13 | margin-bottom: 5vh; 14 | } 15 | .title { 16 | margin-top: 10vh; 17 | margin-bottom: 5vh; 18 | font-size: 2em; 19 | } 20 | .link { 21 | text-decoration: none; 22 | margin-bottom: 5vh; 23 | } 24 | .btn { 25 | border: None; 26 | background-color: #00BD67; 27 | padding: 15px 25px; 28 | color: #fff; 29 | font-size: 1.1em; 30 | border-radius: 9px; 31 | margin-top: 12px; 32 | margin-right: 1vh; 33 | } 34 | .student { 35 | margin-bottom: 5vh; 36 | } 37 | .students { 38 | font-size: 1.5em; 39 | } -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import './App.css'; 2 | import Home from './components/Home'; 3 | import Login from './components/Login'; 4 | import Profile from './components/Profile'; 5 | import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; 6 | import Dashboard from './components/Dashboard'; 7 | 8 | 9 | function App() { 10 | return ( 11 | 12 | 13 | } /> 14 | } /> 15 | } /> 16 | } /> 17 | 18 | 19 | ); 20 | } 21 | 22 | export default App; -------------------------------------------------------------------------------- /client/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { render, screen } from '@testing-library/react'; 2 | import App from './App'; 3 | 4 | test('renders learn react link', () => { 5 | render(); 6 | const linkElement = screen.getByText(/learn react/i); 7 | expect(linkElement).toBeInTheDocument(); 8 | }); 9 | -------------------------------------------------------------------------------- /client/src/components/Dashboard.js: -------------------------------------------------------------------------------- 1 | import '../App.css'; 2 | import { useEffect, useState } from "react"; 3 | import { Link } from "react-router-dom"; 4 | import { useNavigate } from "react-router-dom"; 5 | import { getSessionToken } from '@descope/react-sdk' 6 | 7 | 8 | function Dashboard() { 9 | const sessionToken = getSessionToken(); // get the session token 10 | const navigate = useNavigate() 11 | const [roles, setRoles] = useState({ 12 | teacherRole: false, 13 | studentRole: false 14 | }) 15 | 16 | useEffect(() => { 17 | fetch('/get_role_data', { // call the api endpoint from the flask server 18 | headers: { 19 | Accept: 'application/json', 20 | Authorization: 'Bearer ' + sessionToken, 21 | } 22 | }).then(data => { 23 | if (data.status === 401) { 24 | navigate('/login') 25 | } 26 | return data.json() 27 | }).then(jsonData => { 28 | setRoles({ 29 | teacherRole: jsonData.valid_teacher, 30 | studentRole: jsonData.valid_student 31 | }) 32 | }).catch((err) => { 33 | console.log(err) 34 | navigate('/login') 35 | }) 36 | }, []) 37 | 38 | return ( 39 |
40 |

Dashboard

41 | Profile 42 | {roles.teacherRole && ( 43 |
44 |

Welcome back Teacher!

45 |

You have 50+ students currently 🧑‍🎓

46 |
47 | )} 48 | {roles.studentRole && ( 49 |
50 |

Welcome back Student!

51 |

Unlucky! You have homework!

52 | 53 |
54 | )} 55 |
56 | ) 57 | } 58 | 59 | 60 | export default Dashboard; -------------------------------------------------------------------------------- /client/src/components/Home.js: -------------------------------------------------------------------------------- 1 | import '../App.css'; 2 | import { useEffect } from "react"; 3 | import { Link } from "react-router-dom"; 4 | import { useSession } from '@descope/react-sdk' 5 | import { useNavigate } from "react-router-dom"; 6 | 7 | function Home() { 8 | const { isAuthenticated } = useSession() 9 | const navigate = useNavigate() 10 | 11 | useEffect(() => { 12 | if (isAuthenticated) { 13 | return navigate("/profile"); 14 | } 15 | }, [isAuthenticated]) // listen for when isAuthenticated has changed 16 | 17 | return ( 18 |
19 |

Home

20 | Login 21 | 22 |
23 | ) 24 | } 25 | 26 | 27 | export default Home; 28 | -------------------------------------------------------------------------------- /client/src/components/Login.js: -------------------------------------------------------------------------------- 1 | import '../App.css'; 2 | import React, { useEffect } from "react"; 3 | import { Descope, useSession, useUser } from '@descope/react-sdk' 4 | import { useNavigate } from "react-router-dom"; 5 | 6 | 7 | function Login() { 8 | // isAuthenticated: boolean - is the user authenticated? 9 | // isSessionLoading: boolean - Use this for showing loading screens while objects are being loaded 10 | const { isAuthenticated, isSessionLoading } = useSession() 11 | // isUserLoading: boolean - Use this for showing loading screens while objects are being loaded 12 | const { isUserLoading } = useUser() 13 | const navigate = useNavigate() 14 | 15 | useEffect(() => { 16 | if (isAuthenticated) { 17 | return navigate("/profile"); 18 | } 19 | }, [isAuthenticated]) // listen for when isAuthenticated has changed 20 | 21 | return ( 22 |
23 | { 24 | (isSessionLoading || isUserLoading) &&

Loading...

25 | } 26 | 27 | {!isAuthenticated && 28 | ( 29 | <> 30 |

Login/SignUp to see the Secret Message!

31 | console.log(e.detail.user)} 34 | onError={(e) => console.log('Could not log in!')} 35 | theme="light" 36 | /> 37 | 38 | ) 39 | } 40 |
41 | ) 42 | } 43 | 44 | 45 | export default Login; 46 | -------------------------------------------------------------------------------- /client/src/components/Profile.js: -------------------------------------------------------------------------------- 1 | import '../App.css'; 2 | import { useState, useEffect, useCallback } from "react"; 3 | import { useDescope, useUser, getSessionToken, useSession } from '@descope/react-sdk' 4 | import { useNavigate } from "react-router-dom"; 5 | import { Link } from "react-router-dom"; 6 | 7 | 8 | function Profile() { 9 | const { isSessionLoading } = useSession() 10 | 11 | const { user } = useUser() 12 | const { logout } = useDescope() 13 | const navigate = useNavigate() 14 | 15 | const [secret, setSecret] = useState({ 16 | secret: "", 17 | roles: [] 18 | }) 19 | 20 | const sessionToken = getSessionToken(); // get the session token 21 | 22 | const logoutUser = useCallback(async () => { 23 | await logout() 24 | return navigate('/login') 25 | }, [logout, navigate]); 26 | 27 | useEffect(() => { 28 | fetch('/get_roles', { // call the api endpoint from the flask server 29 | headers: { 30 | Accept: 'application/json', 31 | Authorization: 'Bearer ' + sessionToken, 32 | } 33 | }).then(data => { 34 | if (data.status === 401) { 35 | navigate('/login') 36 | } 37 | return data.json() 38 | }).then(jsonData => { 39 | setSecret({ 40 | secret: jsonData.secretMessage, 41 | roles: jsonData.roles 42 | }) 43 | }).catch((err) => { 44 | console.log(err) 45 | navigate('/login') 46 | }) 47 | }, []) 48 | 49 | return ( 50 | <> 51 | {user && ( 52 |
53 |
54 |

Hello {user.name} 👋

55 |
My Private Component
56 |

Secret Message: {secret.secret}

57 |

Your Role(s):

58 | {!secret.roles || secret.roles.length === 0 ? 59 |

No role found!

60 | : 61 | secret.roles.map((role, i) => ( 62 |

{role}

63 | )) 64 | } 65 | Home 66 | Dashboard 67 | 68 |
69 |
70 | )} 71 | 72 | ) 73 | } 74 | 75 | 76 | export default Profile; 77 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /client/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import reportWebVitals from './reportWebVitals'; 6 | import { AuthProvider } from '@descope/react-sdk' 7 | 8 | 9 | const root = ReactDOM.createRoot(document.getElementById('root')); 10 | root.render( 11 | 12 | 13 | 14 | 15 | 16 | ); 17 | 18 | // If you want to start measuring performance in your app, pass a function 19 | // to log results (for example: reportWebVitals(console.log)) 20 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 21 | reportWebVitals(); 22 | -------------------------------------------------------------------------------- /client/src/reportWebVitals.js: -------------------------------------------------------------------------------- 1 | const reportWebVitals = onPerfEntry => { 2 | if (onPerfEntry && onPerfEntry instanceof Function) { 3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 4 | getCLS(onPerfEntry); 5 | getFID(onPerfEntry); 6 | getFCP(onPerfEntry); 7 | getLCP(onPerfEntry); 8 | getTTFB(onPerfEntry); 9 | }); 10 | } 11 | }; 12 | 13 | export default reportWebVitals; 14 | -------------------------------------------------------------------------------- /client/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flask-react-sample-app", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": {} 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flask-react-frontend", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "setup": "cd client && npm install && cd .. && cd server && make setup", 8 | "client": "cd client && npm start", 9 | "server": "cd server && cd server && poetry run python app.py" 10 | }, 11 | "dependencies": { 12 | "@descope/react-sdk": "^1.0.3", 13 | "@testing-library/jest-dom": "^5.16.5", 14 | "@testing-library/react": "^13.4.0", 15 | "@testing-library/user-event": "^13.5.0", 16 | "react": "^18.2.0", 17 | "react-dom": "^18.2.0", 18 | "react-scripts": "5.0.1", 19 | "web-vitals": "^2.1.4" 20 | } 21 | } -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "local>descope-sample-apps/renovate-config" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /server/.env.example: -------------------------------------------------------------------------------- 1 | PROJECT_ID="YOUR_DESCOPE_PROJECT_ID" 2 | -------------------------------------------------------------------------------- /server/Makefile: -------------------------------------------------------------------------------- 1 | VENV = venv 2 | PYTHON = $(VENV)/bin/python3 3 | 4 | 5 | setup: 6 | python3 -m venv $(VENV) 7 | . $(VENV)/bin/activate 8 | pip3 install poetry 9 | poetry install 10 | 11 | -------------------------------------------------------------------------------- /server/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/server/README.md -------------------------------------------------------------------------------- /server/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "server" 3 | version = "0.1.0" 4 | description = "Using the Python framework Flask + React.js + Descope Python SDK to add and manage basic authentication and roles. The project will feature multiple pages, protected routes, and logout functionality." 5 | authors = ["Descope "] 6 | readme = "README.md" 7 | 8 | [tool.poetry.dependencies] 9 | python = "^3.10" 10 | flask = "^2.3.2" 11 | descope = "^1.5.5" 12 | python-dotenv = "^1.0.0" 13 | 14 | 15 | [build-system] 16 | requires = ["poetry-core"] 17 | build-backend = "poetry.core.masonry.api" 18 | -------------------------------------------------------------------------------- /server/server/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.1.0" -------------------------------------------------------------------------------- /server/server/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | from flask import Flask, request, make_response, jsonify 3 | from descope import DescopeClient 4 | from functools import wraps 5 | 6 | 7 | app = Flask(__name__) # initialize flask app 8 | 9 | 10 | try: 11 | descope_client = DescopeClient(project_id=os.environ.get("PROJECT_ID")) # initialize the descope client 12 | except Exception as error: 13 | print ("failed to initialize. Error:") 14 | print (error) 15 | 16 | 17 | def token_required(f): # auth decorator 18 | @wraps(f) 19 | def decorator(*args, **kwargs): 20 | session_token = None 21 | 22 | if 'Authorization' in request.headers: # check if token in request 23 | auth_request = request.headers['Authorization'] 24 | session_token = auth_request.replace('Bearer ', '') 25 | if not session_token: # throw error 26 | return make_response(jsonify({"error": "❌ invalid session token!"}), 401) 27 | 28 | try: # validate token 29 | jwt_response = descope_client.validate_session(session_token=session_token) 30 | except: 31 | return make_response(jsonify({"error": "❌ invalid session token!"}), 401) 32 | 33 | return f(jwt_response, *args, **kwargs) 34 | 35 | return decorator 36 | 37 | 38 | @app.route('/get_roles', methods=['GET']) 39 | @token_required 40 | def get_roles(jwt_response): 41 | roles = jwt_response["roles"] 42 | 43 | return { "secretMessage": "You are now a trained Descope user!", "roles": roles} 44 | 45 | 46 | @app.route('/get_role_data', methods=['GET']) 47 | @token_required 48 | def get_role_data(jwt_response): 49 | valid_student_role = descope_client.validate_roles( 50 | jwt_response, ["student"] 51 | ) 52 | valid_teacher_role = descope_client.validate_roles( 53 | jwt_response, ["teacher"] 54 | ) 55 | 56 | return {"valid_teacher": valid_teacher_role, "valid_student": valid_student_role} 57 | 58 | 59 | if __name__ == '__main__': 60 | app.run(debug=True) -------------------------------------------------------------------------------- /server/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/descope-sample-apps/flask-react-sample-app/e5cd22213f0ce550819191e927f3da9cc7be711b/server/tests/__init__.py --------------------------------------------------------------------------------