From d5bb51d3b954360357e7abc396c6b4c8c4107cbf Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: Thu, 11 Jan 2024 21:04:03 +0100 Subject: [PATCH 1/3] Update README.md --- README.md | 64 +++++++++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 401f376..edabe4d 100644 --- a/README.md +++ b/README.md @@ -2,88 +2,88 @@ # JWT Authentication With Flask & React.js -Almost every website in the world has user authentication, in this project you have to implement user authentication using the Python Flask framework for building a backend REST API and React.js and sessionStorage API for the front end web application. +Almost every website in the world has user authentication. In this project, you have to implement user authentication using the Python Flask framework for building a backend REST API and React.js, and *sessionStorage* API for the frontend web application. -## 🗒️ Instructions +## 📝 Instructions Implement an authentication system with the following parts: -1. **Signup**: The user must be able to pick its email, any password and submit the form, a new user must be created in the database and the user must be redirected to the login form afterwards. -2. **Login**: The user fills out its email, and password and it's redirected to the private dashboard after successfull authentication. -3. **Validation**: Any page considered "private" must always validate that the current user is valid, if not, the page must redirect the user back to login. -4. **Logout**: Any moment the user must be able to press "logout" in the navbar, and it will get redirected back to the login path. +1. **Signup**: The user must be able to pick their email, a password and submit the form; a new user must be created in the database, then the user must be redirected to the login form afterwards. +2. **Login**: The user fills out their email and password, then it's redirected to the private dashboard after a successful authentication. +3. **Validation**: Any page considered "private" must always validate that the current user is valid; if not, the page must redirect the user back to the login page. +4. **Logout**: At any moment the user must be able to press "logout" in the navbar, and it will get redirected back to the login path. -At least the following pages and react components must be implemented into the project: +At least the following pages and React components must be implemented into the project: -| Path | Component | Functionality | -| --------- | ----------- | ----------------------------------------------------------------- | -| `/signup` | `` | Renders the signup form | -| `/login` | `` | Renders the login form | -| `/private`| `` | Validates that only authenticated users and render this component | +| Path | Component | Functionality | +| --------- | ----------- | ----------------------------------------------------------------- | +| `/signup` | `` | Renders the signup form | +| `/login` | `` | Renders the login form | +| `/private` | `` | Validates that only authenticated users can enter and renders this component | -## 🌱 How to start this project +## 🌱 How to start this project Do not clone this repository because we are going to be using a different template. -We recommend opening the `React.js + Flask API boilerplate ` using a provisioning tool like [Codespaces](https://4geeks.com/lesson/what-is-github-codespaces) (recommended) or [Gitpod](https://4geeks.com/lesson/how-to-use-gitpod). Alternatively, you can clone it on your local computer using the `git clone` command. +We recommend opening the `React.js + Flask API boilerplate` using a provisioning tool like [Codespaces](https://4geeks.com/lesson/what-is-github-codespaces) (recommended) or [Gitpod](https://4geeks.com/lesson/how-to-use-gitpod). Alternatively, you can clone it on your local computer using the `git clone` command. This is the repository you need to open or clone: -``` +```text https://github.com/4GeeksAcademy/react-flask-hello ``` **👉 Please follow these steps on** [how to start a coding project](https://4geeks.com/lesson/how-to-start-a-project). -💡 Important: Remember to save and upload your code to GitHub by creating a new repository, updating the remote (`git remote set-url origin `), and uploading the code to your new repository using the `add`, `commit` and `push` commands from the git terminal. +> 💡 Important: Remember to save and upload your code to GitHub by creating a new repository, updating the remote (`git remote set-url origin `), and uploading the code to your new repository using the `add`, `commit` and `push` commands from the git terminal. ## More details about the authentication: -Usually an authentication system is implemented in 4 parts: +Usually, an authentication system is implemented in 4 parts: ![Authentication Diagram](https://github.com/breatheco-de/jwt-authentication-with-flask-react/blob/main/.learn/login_diagram.jpeg?raw=true) ### User signup -At the beginning of every application that is not users or tokens, so the first step that makes sense to build is user signup. +At the beginning of every application, there are no users or tokens, so the first step that makes sense to build is user signup. 1. The user navigates to the `/signup` path. -2. The React.js application (probably using the React Router library) will detect the route `/signup` and match it with its corresponding React.js page component that will take care of rendering the signup HTML. +2. The React.js application (probably using the React Router library) will detect the route `/signup` and match it with its corresponding React.js page component, which will take care of rendering the signup HTML. 3. The user picks and writes an email and password and clicks submit. -4. The React.js page is listening to the onSubmit event, it gets triggered and the handleSubmit function fetches the email and password to the backend Python Flask API, probably doing a `POST /token` request with the email and password on the body payload. +4. The React.js page is listening for the `onSubmit` event; it gets triggered and the `handleSubmit` function fetches the email and password to the backend Python Flask API, probably doing a `POST /token` request with the email and password on the body's payload. ### User login (start session) This part of the process occurs only when new tokens have to be generated. -1. The user lands in the myapplication.com/login path. -2. The React.js application (probably using the React Router library) will detect the `/login` path and match it with its corresponding React.js page component, this page will take care of rendering the login form. +1. The user lands in the `myapplication.com/login` path. +2. The React.js application (probably using the React Router library) will detect the `/login` path and match it with its corresponding React.js page component; this page will take care of rendering the login form. 3. The user fills out the login form and submits it. 4. The page is listening (waiting) for the form submit event to trigger, and it finally triggers because the user submits the form. 5. The page now retrieves the username and password information and fetch (POST) that data to the API. 6. The API validates that the username and password are correct and returns a `token` object. -7. The front-end application saves that token in the sessionStorage. -8. The front end application redirects to the `/private`. +7. The front-end application saves that token in the `sessionStorage`. +8. The front-end application redirects to the `/private`. ### User logout (end session) This process occurs when the user desires to logout. -1. Normally there is a button to log out somewhere in your application. -2. The user press that button and the onClick event handler is called. -3. The front-end application removes the token from the sessionStorage. +1. Normally, there is a button to log out somewhere in your application. +2. The user presses that button, and the `onClick` event handler is called. +3. The front-end application removes the token from the `sessionStorage`. 4. The front-end application redirects to the home page (public). ### Token Validation -Any user can just type `/private` to attempt visiting a private page, that is why we need to implement a validation that prevents anonymous users to see the content of this page, and we must redirect the user to `/login` or any other **public** page. This is usually how the process goes: +Any user can just type `/private` to attempt visiting a private page. That is why we need to implement a validation that prevents anonymous users from seeing the content of this page, and we must redirect the user to `/login` or any other **public** page. This is usually how the process goes: -1. The user types any private URL, for example: myapplication.com/private +1. The user types any private URL, for example: `myapplication.com/private`. 2. The React.js application (probably using the React Router library) will detect the route `/private` and match it with its corresponding React.js page component that will take care of rendering the HTML. -3. Before rendering the HTML -and only because this is a private route- the component must verify that the sessionStorage contains the authenticated token, you normally would do that in the useEffect (component did mount) because you want to do it very early during the application loading. -4. If sessionStorage 👎 **does not** have the token, the current user is not considered to be logged in and the component must redirect to the login view. -5. If the sessionStorage 👍 does contain the token, the current user is successfully logged in and the rest of the `/private` view component is loaded. +3. Before rendering the HTML -and only because this is a private route- the component must verify that the `sessionStorage` contains the authenticated token. You normally would do that in the `useEffect` because you want to do it very early during the application loading. +4. If `sessionStorage` 👎 **does not** have the token, the current user is not considered to be logged in and the component must redirect to the login view. +5. If the `sessionStorage` 👍 does contain the token, the current user is successfully logged in, and the rest of the `/private` view component is loaded. This and many other projects are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sanchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). From 8be7be45f7d57f280feebd7239c09766ed71234f Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: Thu, 11 Jan 2024 21:19:12 +0100 Subject: [PATCH 2/3] Update README.es.md --- README.es.md | 60 +++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/README.es.md b/README.es.md index fa99f82..2f6e492 100644 --- a/README.es.md +++ b/README.es.md @@ -2,46 +2,44 @@ # Autenticación JWT con Flask y React.jsy -Casi todos los sitios web en el mundo tienen autenticación de usuarios, en este proyecto debes realizar una aplicación web implementando la autenticación de usuarios usando Python y el framework Flask para construir un back-end de REST API y React.js, y sessionStorage API para el Front-end. +Casi todos los sitios web en el mundo tienen autenticación de usuarios, en este proyecto debes realizar una aplicación web implementando la autenticación de usuarios usando Python y el framework Flask para construir un back-end de REST API y React.js, y *sessionStorage* API para el front-end. -El uso de [esta plantilla/boilerplate](https://github.com/4GeeksAcademy/react-flask-hello) es recomendada para comenzar el desarrollo, ya viene preparada con todas las condiciones e instalaciones para comenzar a programar en un minuto. - -## 🗒️ Instrucciones +## 📝 Instrucciones Implementa un sistema de autenticación en las siguientes partes: -1. **Registro**: El usuario deberá poder colocar un correo, cualquier contraseña y enviar el formulario, un nuevo usuario debe ser creado en la base de datos y el usuario debe ser redireccionado al inicio de sesión luego de esto. +1. **Registro**: El usuario deberá poder colocar un correo, una contraseña y enviar el formulario, un nuevo usuario debe ser creado en la base de datos y el usuario debe ser redireccionado al inicio de sesión luego de esto. 2. **Inicio de Sesión**: El usuario debe llenar su correo y contraseña y debe ser redirigido a un menú privado luego de que la autenticación sea exitosa. 3. **Validación**: Cualquier página considerada "privada" siempre debe estar validando que el usuario actual es válido, si no, la página debe redirigir al inicio de sesión. 4. **Cierre de Sesión**: Cualquier momento que el usuario presione el "cierre de sesión" en la barra de navegación (navbar) se debe redirigir a la ruta del inicio de sesión. -Al menos las siguientes páginas y componentes de react deben ser implementados en el proyecto: +Al menos las siguientes páginas y componentes de React deben ser implementados en el proyecto: -| Ruta | Componente | Funcionalidad | -| --------- | ----------- | ----------------------------------------------------------------- | -| `/signup` | `` | Renderizar formulario de registro | -| `/login` | `` | Renderizar formulario de Inicio de sesión | -| `/private`| `` | Validar que solo ingresen usuarios autenticados y renderizar este componente | +| Ruta | Componente | Funcionalidad | +| --------- | ----------- | ----------------------------------------------------------------- | +| `/signup` | `` | Renderizar formulario de registro | +| `/login` | `` | Renderizar formulario de Inicio de sesión | +| `/private` | `` | Validar que solo ingresen usuarios autenticados y renderizar este componente | ## 🌱 Cómo comenzar este proyecto No clones este repositorio porque vamos a usar una plantilla diferente. -Recomendamos abrir el `React.js + Flask API boilerplate` usando una herramienta de aprovisionamiento como [Codespaces](https://4geeks.com/es/lesson/tutorial-de-github-codespaces) (recomendado) o [Gitpod](https://4geeks.com/es/lesson/como-utilizar-gitpod). Alternativamente, puedes clonarlo en tu computadora local usando el comando `git clone`. +Recomendamos abrir el `React.js + Flask API boilerplate` usando un entorno de desarrollo como [Codespaces](https://4geeks.com/es/lesson/tutorial-de-github-codespaces) (recomendado) o [Gitpod](https://4geeks.com/es/lesson/como-utilizar-gitpod). Alternativamente, puedes clonarlo en tu computadora local usando el comando `git clone`. Este es el repositorio que necesitas abrir o clonar: -``` +```text https://github.com/4GeeksAcademy/react-flask-hello ``` -**👉 Por favor sigue estos pasos** [cómo comenzar un proyecto de codificación](https://4geeks.com/es/lesson/como-comenzar-un-proyecto-de-codificacion). +**👉 Por favor sigue estos pasos sobre** [cómo comenzar un proyecto de programación](https://4geeks.com/es/lesson/como-comenzar-un-proyecto-de-codificacion). -💡 Importante: Recuerda guardar y subir tu código a GitHub creando un nuevo repositorio, actualizando el remoto (`git remote set-url origin `) y subiendo el código a tu nuevo repositorio usando los comandos `add`, `commit` y `push` desde la terminal de git. +> 💡 Importante: Recuerda guardar y subir tu código a GitHub creando un nuevo repositorio, actualizando el remoto (`git remote set-url origin `) y subiendo el código a tu nuevo repositorio usando los comandos `add`, `commit` y `push` desde la terminal de git. ## Más detalles sobre la autenticación: -Usualmente un sistema de autenticación es implementado en 4 partes: +Usualmente, un sistema de autenticación es implementado en 4 partes: ![Diagrama de Autenticación](https://github.com/breatheco-de/jwt-authentication-with-flask-react/blob/main/.learn/login_diagram.jpeg?raw=true) @@ -52,19 +50,19 @@ Al principio de cada aplicación no hay usuario o tokens, así que el primer pas 1. El usuario navega a la ruta `/signup`. 2. La aplicación de React.js (probablemente usando la librería React Router) deberá detectar la ruta `/signup` y realizará emparejado con el correspondiente componente de página de React.js, esta página se encargará de representar el HTML del registro. 3. El usuario escoge y escribe un correo electrónico, una contraseña y hace clic en enviar. -4. La página de React.js está a la espera del evento onSubmit, este al activarse la función handleSubmit obtiene el email y contraseña de la API del Backend con python y flask, probablemente usanto una petición `POST /token` con el email y contraseña en el body payload. +4. La página de React.js está a la espera del evento `onSubmit`, este activa la función `handleSubmit` que obtiene el email y contraseña de la API del backend con Python y flask, probablemente usando una petición `POST /token` con el email y contraseña en el body payload. ### Inicio de sesión Esta parte del proceso ocurre solo cuando los nuevos tokens fueron generados. -1. El usuario aterriza en la ruta miaplicacion.com/login. -2. La aplicación de React.js (probablemente usando la libreria React Router) deberá detectar la ruta `/login` y realizará un emparejado con el correspondiente componente de página de React.js, esta página se encargará de renderizar el formulario de inicio de sesión. -3. El usuario llena formulario de inicio de sesión y lo envía. +1. El usuario aterriza en la ruta `miaplicacion.com/login`. +2. La aplicación de React.js (probablemente usando la librería React Router) deberá detectar la ruta `/login` y realizará un emparejado con el correspondiente componente de página de React.js, esta página se encargará de renderizar el formulario de inicio de sesión. +3. El usuario llena el formulario de inicio de sesión y lo envía. 4. La página está esperando a que se active el evento de envío del formulario, y finalmente se activa porque el usuario envía el formulario. 5. La página ahora recopila la información del nombre de usuario y contraseña para subir (POST) la data a la API. -6. La API válida que nombre de usuario y contraseña sean correctos y regresa un objeto `token`. -7. El front-end de la aplicación guarda el token en el sessionStorage. +6. La API valida que nombre de usuario y contraseña sean correctos y regresa un objeto `token`. +7. El front-end de la aplicación guarda el token en el `sessionStorage`. 8. El front-end de la aplicación redirecciona a la ruta `/private`. ### Cierre de sesión @@ -72,18 +70,18 @@ Esta parte del proceso ocurre solo cuando los nuevos tokens fueron generados. Este proceso ocurre cuando el usuario desea cerrar la sesión. 1. Normalmente, hay un botón para el cierre de sesión en algún lado de la aplicación. -2. El usuario presiona el botón y el controlador de eventos onClick es llamado. -3. El front-end de la aplicación elimina el token del sessionStorage. +2. El usuario presiona el botón y el controlador de eventos `onClick` es llamado. +3. El front-end de la aplicación elimina el token del `sessionStorage`. 4. El front-end de la aplicación redirige a la página de inicio (público). ### Validación del Token -Cualquier usuario puede solo tipear `/private` para intentar visitar una página privada, por eso es que se necesita implementar una validación, para prevenir que usuarios anonimos vean el contenido de la página privada, y debemos redirigir al usuario a la ruta `/login` o a otra página **pública**. Asi es como usualmente es el proceso: +Cualquier usuario puede solo escribir `/private` para intentar visitar la página privada, por eso es que se necesita implementar una validación, para prevenir que usuarios anónimos vean el contenido de la página privada, y debemos redirigir al usuario a la ruta `/login` o a otra página **pública**. Así es como usualmente es el proceso: -1. El usuario tipea cualquier URL privada, por ejemplo: myapplication.com/private -2. La aplicación de React.js (probablemente usando la libreria React Router) detectará la ruta `/private` y realizara un emparejado con el correspondiente componente de página de React.js que se encargará de renderizar el HTML. -3. Antes de renderizar el HTML -y solo porque esta es una ruta privada- el componente debe verificar que el sessionStorage contiene un token autenticado, normalmente esto se haria en el useEffect (component did mount) porque se quiere que se haga tan pronto la aplicación cargue. -4. Si el sessionStorage 👎 **no** tiene el token, el usuario actual no está considerado como registrado y el componente debe redirigirlo a la vista del inicio de sesión. -5. Si el sessionStorage 👍 contiene el token, el actual usuario está registrado exitosamente y el resto de la vista del componente `/private` es cargado. +1. El usuario escribe cualquier URL privada, por ejemplo: `miaplicacion.com/private`. +2. La aplicación de React.js (probablemente usando la librería React Router) detectará la ruta `/private` y realizará un emparejado con el correspondiente componente de página de React.js que se encargará de renderizar el HTML. +3. Antes de renderizar el HTML -y solo porque esta es una ruta privada- el componente debe verificar que el `sessionStorage` contiene un token autenticado, normalmente esto se haría en el `useEffect` porque se quiere que se haga tan pronto la aplicación cargue. +4. Si el `sessionStorage` 👎 **no** tiene el token, el usuario actual no está considerado como registrado y el componente debe redirigirlo a la vista del inicio de sesión. +5. Si el `sessionStorage` 👍 contiene el token, el actual usuario está registrado exitosamente y el resto de la vista del componente `/private` es cargado. -Este y otros proyectos son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Curso de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). \ No newline at end of file +Este y otros proyectos son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). From 28b85c7fb159282cac4990e36f6bb8d8fa99f22d Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: Thu, 11 Jan 2024 21:20:19 +0100 Subject: [PATCH 3/3] Update README.es.md --- README.es.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.es.md b/README.es.md index 2f6e492..a7bc1f9 100644 --- a/README.es.md +++ b/README.es.md @@ -1,5 +1,5 @@ -# Autenticación JWT con Flask y React.jsy +# Autenticación JWT con Flask y React.js Casi todos los sitios web en el mundo tienen autenticación de usuarios, en este proyecto debes realizar una aplicación web implementando la autenticación de usuarios usando Python y el framework Flask para construir un back-end de REST API y React.js, y *sessionStorage* API para el front-end.