I am creating a simple web app using flask. I will be hosting it on my linux server.
The web-app does multiple user specific things. Like list directories in Users home, add ssh-keys for user and stuff like that.
I would like to know if there is a way for flask to open a login page, and the user-name and password be validated based on system user-name and password. (i.e that users system credentials). If yes, then how. If no then what else can I do?
Using ’simplepam’ python package you can authenticate against PAM system on linux. Here is flask basic example which I have modifed to use simplepam:
from flask import Flask, session, redirect, url_for, escape, request
from simplepam import authenticate
app = Flask(__name__)
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if authenticate(str(username), str(password)):
session['username'] = request.form['username']
return redirect(url_for('index'))
else:
return 'Invalid username/password'
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=password name=password>
<p><input type=submit value=Login>
</form>
'''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
if __name__ == '__main__':
app.run(debug='True')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With