Skip to content

Instantly share code, notes, and snippets.

@sudodo
Created October 16, 2023 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudodo/4fe7574d7fa899dbbbb32ff957833063 to your computer and use it in GitHub Desktop.
Save sudodo/4fe7574d7fa899dbbbb32ff957833063 to your computer and use it in GitHub Desktop.
Login authentication for React & Flask app

To ensure that only logged-in users can see the update_user page, you'll need to implement authentication checks. This typically involves sending the token (that you've stored in localStorage after login) with each request to your backend and verifying it there. Here's how you can achieve this:

  1. Send Token in Request from React: Modify your API calls to include the authentication token in the headers. With Axios, it might look something like this:

    import axios from "axios";
    
    const token = localStorage.getItem('token');
    
    axios.get('/api/update_user', { headers: { Authorization: `Bearer ${token}` } })
        .then(response => {
            // handle success
        })
        .catch(error => {
            // handle error
            if (error.response && error.response.status === 401) {
                // if unauthorized, redirect to login or show error
            }
        });
  2. Verify Token in Flask: On your Flask backend, you'll need to verify the token for each request that should be authenticated. You can use Flask decorators to create protected routes:

    from flask import Flask, request, jsonify, make_response
    import jwt  # used for encoding and decoding jwt tokens
    
    app = Flask(__name__)
    
    def token_required(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            token = None
            
            # jwt is passed in the request header
            if 'Authorization' in request.headers:
                token = request.headers['Authorization'].split(" ")[1]
    
            if not token:
                return jsonify({'message': 'Token is missing!'}), 401
    
            try:
                # Decode token here (you need the same secret used to encode it)
                jwt.decode(token, app.config['SECRET_KEY'])
            except:
                return jsonify({'message': 'Token is invalid!'}), 401
    
            return f(*args, **kwargs)
    
        return decorated
    
    @app.route('/api/update_user')
    @token_required
    def update_user():
        # your code here
  3. Protecting React Routes: You can also protect your React routes by creating PrivateRoute components. This component would check if the token exists (or is valid) before allowing the user to access the route.

    import React from 'react';
    import { Route, Redirect } from 'react-router-dom';
    
    const PrivateRoute = ({component: Component, ...rest}) => {
        return (
            <Route 
                {...rest}
                render={props => 
                    localStorage.getItem('token') ? (
                        <Component {...props} />
                    ) : (
                        <Redirect 
                            to={{ 
                                pathname: "/login", 
                                state: { from: props.location } 
                            }} 
                        />
                    )
                }
            />
        );
    };
    
    export default PrivateRoute;

    Then, use this PrivateRoute component in your main router file for the update_user path:

    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    import PrivateRoute from './PrivateRoute';
    import UpdateUser from './UpdateUser';
    import Login from './Login';
    
    function App() {
        return (
            <Router>
                <Switch>
                    <Route path="/login" component={Login} />
                    <PrivateRoute path="/update_user" component={UpdateUser} />
                    {/* other routes here */}
                </Switch>
            </Router>
        );
    }
    
    export default App;

In this setup, the update_user API is protected by the token, and the update_user page in React is only accessible to users who have a valid token. This effectively ensures that only logged-in users can see the update_user page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment