From a5681a4b850b198107d025213c5c8d26cd5634d2 Mon Sep 17 00:00:00 2001 From: Javier Sánchez Parra Date: Wed, 1 Dec 2021 09:15:51 +0100 Subject: Add multi user support It is inspired by the following example: https://github.com/maxcountryman/flask-login/blob/c760c0ef7ccc95d49b4693200245a4f2b148d41b/README.md#usage --- ogcp/cfg/ogcp.json | 12 ++++++++++-- ogcp/models.py | 4 ++-- ogcp/views.py | 36 ++++++++++++++++++++++++++---------- 3 files changed, 38 insertions(+), 14 deletions(-) (limited to 'ogcp') diff --git a/ogcp/cfg/ogcp.json b/ogcp/cfg/ogcp.json index 66a5304..b5f3606 100644 --- a/ogcp/cfg/ogcp.json +++ b/ogcp/cfg/ogcp.json @@ -2,6 +2,14 @@ "IP": "127.0.0.1", "PORT": 8888, "API_TOKEN": "c3fe7bb0395747ec42a25df027585871", - "USER": "user", - "PASS": "pass" + "USERS": [ + { + "USER": "admin", + "PASS": "pass" + }, + { + "USER": "user", + "PASS": "pass" + } + ] } diff --git a/ogcp/models.py b/ogcp/models.py index 943ed94..9ad40db 100644 --- a/ogcp/models.py +++ b/ogcp/models.py @@ -8,5 +8,5 @@ from flask_login import UserMixin class User(UserMixin): - def get_id(self): - return 1 + def __init__(self, username): + self.id = username diff --git a/ogcp/views.py b/ogcp/views.py index 06f28b2..31b97b0 100644 --- a/ogcp/views.py +++ b/ogcp/views.py @@ -154,12 +154,31 @@ def get_scopes(ips=set()): return scopes, clients -@login_manager.user_loader -def load_user(user_id): - if user_id == 1: - return User() +def authenticate_user(username, pwd): + for user in app.config['USERS']: + if user.get("USER") == username: + if user.get("PASS") == pwd: + return user + else: + flash(_('Incorrect password')) + return None + flash(_('Incorrect user name')) + return None + +def get_user(username): + for user in app.config['USERS']: + if user.get("USER") == username: + return user return None +@login_manager.user_loader +def load_user(username): + if not get_user(username): + return None + + user = User(username) + return user + @app.before_request def load_config(): g.server = OGServer() @@ -194,15 +213,12 @@ def index(): def login(): form = LoginForm(request.form) if request.method == 'POST' and form.validate(): - user = User() form_user = request.form['user'] pwd = request.form['pwd'] - if form_user != app.config['USER']: - flash(_('Incorrect user name')) - return render_template('auth/login.html', form=form) - if pwd != app.config['PASS']: - flash(_('Incorrect password')) + user_dict = authenticate_user(form_user, pwd) + if not user_dict: return render_template('auth/login.html', form=form) + user = User(form_user) login_user(user) return redirect(url_for('index')) return render_template('auth/login.html', form=LoginForm()) -- cgit v1.2.3-18-g5258