Files
flask_test/flask_ldap.py
2023-04-26 19:12:33 +02:00

52 lines
1.4 KiB
Python

from flask import Flask, render_template, request, redirect, session
from ldap3 import Server, Connection, ALL
app = Flask(__name__)
app.secret_key = 'replace_with_a_random_secret_key'
# LDAP server configuration
LDAP_SERVER = 'ipa.example.com'
LDAP_PORT = 389
LDAP_BASE_DN = 'cn=users,cn=accounts,dc=example,dc=com'
@app.route('/')
def home():
return render_template('home.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if authenticate(username, password):
session['username'] = username
return redirect('/dashboard')
else:
return render_template('login.html', error='Invalid credentials')
else:
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'username' in session:
return render_template('dashboard.html', username=session['username'])
else:
return redirect('/login')
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect('/')
def authenticate(username, password):
try:
server = Server(LDAP_SERVER, port=LDAP_PORT, get_info=ALL)
conn = Connection(server, f'uid={username},{LDAP_BASE_DN}', password)
conn.bind()
return True
except:
return False
if __name__ == '__main__':
app.run(debug=True)