防止用户直接访问url,如果未登录Flask则重定向到登录

Rag*_*iya 4 javascript python flask

所以我有一个烧瓶应用程序,在主页中我正在呈现一个登录页面以进行登录。登录后,他们会得到一个需要填写的表格。当他们稍后在表单提交过程中登录时,我还会使用用户名值。这是我的相关烧瓶代码:

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('Login_new.html')
    
@app.route('/login', methods=['POST'])
def logger():
    if request.method == 'POST':
        global user
        user = request.form['username']
        passwrd = request.form['password']

        if (user=="admin") and (passwrd=="VendorAdmin2021"):
            return redirect(url_for("admin.index"))
        
        url = "api for authentication"
        response = requests.post(url, json={"username": user,"password": passwrd}, verify=False)
        #data = response.json()
        print(response.status_code)
        
        if response.status_code == 200:
            return redirect(url_for("test"))
        else:
            flash('Wrong')
            return render_template('Login_new.html')
Run Code Online (Sandbox Code Playgroud)

测试 url 包含实际的表单。这是 Login_new.html 文件:

<html>

<head>
  <link rel="stylesheet" href="/static/style2.css">
  
  <title>Sign in</title>
</head>

<body>
  <div class="main">
    <p class="sign" align="center">Novartis</p>
    <form class="form1" action="/login" method="POST" id="myForm">
      <input class="un " type="text" align="center" placeholder="5-2-1 id" name="username">
      <input class="pass" type="password" align="center" placeholder="Password" name="password">
      <input type="submit" value="Log in" class="submit">
         
                
    </div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.12.5/dist/sweetalert2.all.min.js"></script>

{% with messages = get_flashed_messages() %}
    {% if messages %}
    <script>
      var messages = {{ messages | safe }};
      if (messages=="Wrong"){
          swal.fire({
            title:"Invalid id or password!",
            text:"Please make sure you are connected to the Company Intranet",
            icon:"error",
            closeOnConfirm: false
            });
      }
    </script>
  {% endif %}
{% endwith %}

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

如果用户遵循设定的程序,一切都会正常,但如果他们直接在浏览器中输入测试网址,他们就会绕过登录表单,随后我也无法记录他们的用户名。类似地,对于flask-admin url,如果他们输入管理凭据,他们将被重定向到管理url,但如果他们直接输入管理url,他们可以在没有任何凭据的情况下访问它。我怎样才能防止这种情况发生?

编辑:我尝试使用会话来实现所需的结果,我尝试遵循此https://techmonger.github.io/10/flask-simple-authentication/。这是我现在的代码:

if response.status_code == 200:
            session["logged_in"] = True
            return redirect(url_for("test"))
        else:
            flash('Wrong')
            return render_template('Login_new.html')
Run Code Online (Sandbox Code Playgroud)

并在测试网址中:

@app.route('/test')
def test():
    if not session.get('logged_in'):
        return render_template('Login_new.html')
    form = vendorForm()
Run Code Online (Sandbox Code Playgroud)

现在我收到错误,会话没有属性 get。请帮助,我已经被困在这个问题上太久了

Zin*_*fan 8

您可以使用自己的自定义装饰器,例如在 Flask 登录模块中。与此类似的东西,

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('username') is None or session.get('if_logged') is None:
            return redirect('/login',code=302)
        return f(*args, **kwargs)
    return decorated_function
Run Code Online (Sandbox Code Playgroud)

然后在需要登录的路由中这样使用,

@app.route('/', methods=['GET', 'POST'])
@login_required
def home():
   #blah_blah
Run Code Online (Sandbox Code Playgroud)

它的作用是,每当你调用 url '/' 时,它都会调用 login_required() 包装器中存在的decorated_function()。因此,请将您的登录逻辑放入 deccolated_function() 中。检查用户是否使用会话 cookie(或任何您想要的方法)登录,如果未登录则重定向到登录,否则不返回任何内容。

关于 session.get() 错误,您是否从模块 Flask 导入会话?语法似乎正确