S
S
Spoon in the brain2019-06-08 12:30:01
Python
Spoon in the brain, 2019-06-08 12:30:01

Implementing authorization in flask?

Good afternoon, I have a code for a simple username check:

@app.route('/')
def index():
    return render_template('index.html')

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

HTML:
<!DOCTYPE html>
<html>
<head>
  <title>Bot</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  <div id="content">
    <form action="/submit" method="POST">
      <input type="text" name="login">
    </form>
    <button id="submit">Submit</button>
  </div>
  <script type="text/javascript">
    $('#submit').click(function(){
      event.preventDefault();
      var method = $('form').attr('method')
      var data = $('form').serialize();
      var action = $('form').attr('action')
      $.ajax({
        method: method,
        url: action,
        data: data,
        success: function(result){
          var msg = JSON.stringify(result);
          alert(msg)
        }
      })
    })
  </script>	
</body>
</html>

So, I need to implement authorization so that when I log in, the authorization page is inactive, while other pages are active.
Will there be simple examples or some advice?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Yakushenko, 2019-06-08
@vessels

from flask import session


@app.route('/')
def index():
    if not session.get('logged_in'):
        return redirect('/submit')
    else:
        return render_template('index.html')


@app.route('/submit', methods = ['POST'])
def post():
    if request.form.get('login') == 'admin':
        session['logged_in'] = True
        return jsonify({'type':'success','msg':'success'})
    return jsonify({'type':'error','msg':'error'})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question