S
S
Spoon in the brain2019-04-30 17:32:26
Flask
Spoon in the brain, 2019-04-30 17:32:26

Implementing a SIMPLE auth token between Flask and React?

Evening at home!
If you knew how this authorization token got me, I don’t understand anything, a bunch of examples in Google (of incomprehensible complexity) did not help me in this matter. And all I need is for some of the routers to be closed for guests, and for authorized ones it was open.
I have a simple flask login (no mongodb, mysql, etc.)

@app.route('/log', methods = ['POST'])
def post():
  if request.form.get('login') == 'admin' and request.form.get('pass') == 'zx23ww':
      return jsonify({'type':'success','msg':'success'})
  return jsonify({'type':'error','msg':'error'})

It seems that I started to understand how to do it on the backend, so Redux slipped me a react. My question is, when will these libraries run out? It's not a day then +20 libraries, I already started thinking about doing something else, not programming ...
So, will there be SIMPLE examples of implementing an authorization token between these two frameworks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-30
@vessels

So, will there be SIMPLE examples of implementing an authorization token between these two frameworks?

There is nowhere easier:
import React from 'react';
import Cookie from 'js-cookie';

class SimpleExample extends React.Component {
  state = {
    isProcessing: false,
    token: Cookie.get('token'),
    data: null,
  };
  
  handleSignIn = () => {
    this.setState({ isProcessing: true });

    fetch('/singin', { 
      method: 'POST',
      data: JSON.stringify({ login: 'admin', pass: 'zx23ww' }),
    })
    .then(res => res.json())
    .then(data => {
      this.setState({
        isProcessing: false,
        token: data.token,
      });
        
      Cookie.set('token', token);
    });
  };
  
  handleLogout = () => {
    Cookie.erase('token');
    this.setState({ token: null });
  };

  handleGetProtectedData = () => {
    fetch('/protected'{
      method: 'GET',
      headers: {
        Authorization: `Bearer ${this.state.token}`,
      },
    })
    .then(res => res.json())
    .then(data => {
      this.setState({ data });
    });
  };

  render() {
    const { isProcessing, token } = this.state;
    
    if (isProcessing) return <div>...initialization</div>;

    const isSignedIn = !!token;

    return isSignedIn ? (
      <div>
        <h1>You're signed in</h1>
        <button onClick={this.handleLogout}>Logout</button>
        <button onClick={this.handleGetProtectedData}>Get protected data</button>
      </div>
    ) : (
      <div>
        <h1>You're not signed in</h1>
        <button onClick={this.handleSignIn}>Sign in</button>
      </div>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question