如何在Flask LDAPloginform功能中登录和注销用户?

问题描述

我正在测试我的flask应用程序以登录和注销。我也使用LDAPloginform登录ldap服务器中的用户

当前,一旦用户输入用户名和密码并登录,我便能够对其进行身份验证,但是当我尝试注销用户时,会收到以下错误消息: >

  File "C:\Users\e136320\AppData\Local\Programs\Python\python38\Lib\site-packages\sqlalchemy\util\compat.py",line 178,in raise_
    raise exception
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'werkzeug.local.LocalProxy' is not mapped

这是我的项目文件夹结构:

flask_app/
        static/
            - css/
            - js/
        templates/
            - base.html
            - home_page.html
            - login.html
    - run.py

这是我的run.py代码

# Flask-sqlAlchemy settings
app.config["sqlALCHEMY_DATABASE_URI"] = BASE_CONfig["sql_URI"]
app.config['sqlALCHEMY_TRACK_MODIFICATIONS'] = False
login_manager = LoginManager(app)  # Setup a Flask-Login Manager
ldap_manager = LDAP3LoginManager(app)
db = sqlAlchemy(app)
moment = Moment(app)
Bootstrap(app)


# Create a dictionary to store the users in when they authenticate
# This example stores users in memory.
users = {}


# Declare an Object Model for the user,and make it comply with the
# flask-login UserMixin mixin.
class User(UserMixin):
    def __init__(self,dn,username,data):
        self.dn = dn
        self.username = username
        self.data = data

    def __repr__(self):
        return self.dn

    def get_id(self):
        return self.dn

# Declare a User Loader for Flask-Login.
# Simply returns the User if it exists in our 'database',otherwise
# returns None.
@login_manager.user_loader
def load_user(id):
    if id in users:
        return users[id]
    return None


# Declare The User Saver for Flask-Ldap3-Login
# This method is called whenever a LDAPLoginForm() successfully validates.
# Here you have to save the user,and return it so it can be used in the
# login controller.
@ldap_manager.save_user
def save_user(dn,data,memberships):
    user = User(dn,data)
    users[dn] = user
    return user


# Declare some routes for usage to show the authentication process.
@app.route('/')
def home():
    # Redirect users who are not logged in.
    if not current_user or current_user.is_anonymous:
        return redirect(url_for('login'))

    # User is logged in,so show them a page with their cn and dn.

    return render_template('home_page.html')


@app.route('/login',methods=['GET','POST'])
def login():
    user = current_user
    # Instantiate a LDAPLoginForm which has a validator to check if the user
    # exists in LDAP.
    form = LDAPLoginForm()
    if form.validate_on_submit():
        login_user(form.user,remember=True)  # Tell flask-login to log them in
        print(current_user.username)
        return redirect('/')  # Send them home
    return render_template("login.html",form=form,user=user)


@app.route('/home')
@login_required
def home_page():
    return render_template('home_page.html')


@app.route('/logout')
@login_required
def logout():
    db.session.delete(current_user)  # In order for this to work,I will have to ADD AND COMMIT A USER AS WELL,OTHERWISE GIVES ERROR
    db.session.commit()
    logout_user()
    #flash('You have been logged out.')
    return redirect('/')


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000,debug=True)

这是我的login.html文件(如果有帮助的话):

{% extends "bootstrap/base.html" %}
{% block html_attribs %} lang="en"{% endblock %}

{% block title %} My_app{% endblock %}

{% block styles %}
{{super()}}
{{moment.include_moment()}}
{% endblock %}

{% block navbar %}
<div class="navbar navbar-default" role="navigation" >
    <div class="containter">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle"
             data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar">Toggle Navigation</span>
                <span class="icon-bar">Toggle Navigation</span>
                <span class="icon-bar">Toggle Navigation</span>
            </button>
            <a class="navbar-brand" href="{{ url_for('home_page')}}"><link rel="stylesheet"  href="/static/bcbsm.jpg"></a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="{{ url_for('home_page')  }}"> Home </a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                {% if current_user.is_authenticated %}
                <li><a href="{{ url_for('logout') }}">Log Out</a></li>
                {%else%}
                <li><a href="{{ url_for('login') }}">Log In</a></li>
                {%endif%}
            </ul>
        </div>
    </div>
</div>
{% endblock %}

我是flask和ldap登录的新手,因此任何信息或建议都将有所帮助。似乎我需要在登录功能中将用户添加到会话中,然后在注销功能删除用户。只是非常困惑。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)