Added first version of 'users' module, fixed LDAP

This commit is contained in:
Ferdinand Thiessen 2020-09-04 01:01:00 +02:00
parent 365677697d
commit 7f6ff3f001
6 changed files with 92 additions and 29 deletions

View File

@ -9,6 +9,7 @@ from ldap3 import SUBTREE, MODIFY_REPLACE, HASHED_SALTED_SHA512
import ssl import ssl
from flaschengeist.system.models.user import User from flaschengeist.system.models.user import User
from flaschengeist import logger
class AuthLDAP(modules.Auth): class AuthLDAP(modules.Auth):
@ -81,16 +82,18 @@ class AuthLDAP(modules.Auth):
def modify_user(self, user: User, password, new_password=None): def modify_user(self, user: User, password, new_password=None):
try: try:
ldap_conn = self.ldap.connect(user.uid, password) dn = user.attributes['DN'].value
modifier = {'givenName': [(MODIFY_REPLACE, [user.firstname])], ldap_conn = self.ldap.connect(dn, password)
'sn': [(MODIFY_REPLACE, [user.lastname])], modifier = {}
'mail': [(MODIFY_REPLACE, [user.mail])], for name, ldap_name in [("firstname", "givenName"),
'displayName': [(MODIFY_REPLACE, [user.display_name])], ("lastname", "sn"),
} ("mail", "mail"),
("display_name", "displayName")]:
if getattr(user, name):
modifier[ldap_name] = [(MODIFY_REPLACE, [getattr(user, name)])]
if new_password: if new_password:
salted_password = hashed(HASHED_SALTED_SHA512, new_password) salted_password = hashed(HASHED_SALTED_SHA512, new_password)
modifier['userPassword'] = [(MODIFY_REPLACE, [salted_password])] modifier['userPassword'] = [(MODIFY_REPLACE, [salted_password])]
ldap_conn.modify(user.dn, modifier) ldap_conn.modify(dn, modifier)
except (LDAPPasswordIsMandatoryError, LDAPBindError): except (LDAPPasswordIsMandatoryError, LDAPBindError):
raise BadRequest raise BadRequest

View File

@ -1,15 +0,0 @@
from flask import Blueprint, request, jsonify
import geruecht.controller.mainController as mc
from geruecht.logger import getDebugLogger
registration = Blueprint("registration", __name__)
mainController = mc.MainController()
debug = getDebugLogger()
@registration.route("/registration", methods=['PUT'])
def __registration():
data = request.get_json()
mainController.setNewRegistration(data)
return jsonify({"ok":"ok"})

View File

@ -0,0 +1,66 @@
from flask import Blueprint, request, jsonify
from werkzeug.exceptions import NotFound, BadRequest
from flaschengeist import logger
from flaschengeist.system.decorator import login_required
from flaschengeist.system.controller import userController
users_bp = Blueprint("users", __name__)
def register():
return users_bp
#################################################
# Routes #
# #
# /users POST: register new #
# GET: get all users #
# /users/<uid> GET: get user with uid #
# PUT: modify user #
# DELETE: remove user #
#################################################
@users_bp.route("/users", methods=['POST'])
def __registration():
logger.debug("Register new User...")
return jsonify({"ok": "ok... well not implemented"})
@users_bp.route("/users", methods=['GET'])
@login_required()
def __list_users(**kwargs):
logger.debug("Retrieve list of all users")
users = userController.get_users()
return jsonify(users)
@users_bp.route("/users/<uid>", methods=['GET'])
@login_required()
def __get_user(uid, **kwargs):
logger.debug("Get information of user {{ {} }}".format(uid))
user = userController.get_user(uid)
if user:
return jsonify(user)
raise NotFound
@users_bp.route("/users/<uid>", methods=['PUT'])
@login_required()#roles=['edit_users'])
def __edit_user(uid, **kwargs):
logger.debug("Modify information of user {{ {} }}".format(uid))
user = userController.get_user(uid)
if not user:
raise NotFound
data = request.get_json()
if 'password' not in data:
raise BadRequest("Password is missing")
for key in ["firstname", "lastname", "display_name", "mail"]:
if key in data:
setattr(user, key, data[key])
new_password = data['new_password'] if 'new_password' in data else None
userController.modify_user(user, data['password'], new_password)
userController.update_user(user)
return jsonify({"ok": "ok"})

View File

@ -26,6 +26,9 @@ for loc in paths:
config.read_dict({ config.read_dict({
'auth': { 'auth': {
'enabled': True 'enabled': True
},
'users': {
'enabled': True
} }
}) })
@ -36,10 +39,10 @@ def configure_app(app):
app.config['SECRET_KEY'] = config.get('FLASCHENGEIST', 'SECRET_KEY', fallback='0a657b97ef546da90b2db91862ad4e29') app.config['SECRET_KEY'] = config.get('FLASCHENGEIST', 'SECRET_KEY', fallback='0a657b97ef546da90b2db91862ad4e29')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{passwd}@{host}/{database}'.format( app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{passwd}@{host}/{database}'.format(
user=config['DATABASE']['user'], user=config['DATABASE']['USER'],
passwd=config['DATABASE']['passwd'], passwd=config['DATABASE']['PASSWORD'],
host=config['DATABASE']['host'], host=config['DATABASE']['HOST'],
database=config['DATABASE']['database'] database=config['DATABASE']['DATABASE']
) )
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

View File

@ -12,9 +12,14 @@ def login_user(username, password):
user = User(uid=username) user = User(uid=username)
db.session.add(user) db.session.add(user)
if current_app.config['FG_AUTH_BACKEND'].login(user, password): if current_app.config['FG_AUTH_BACKEND'].login(user, password):
current_app.config['FG_AUTH_BACKEND'].update_user(user) update_user(user)
db.session.commit()
return user return user
return None
def update_user(user):
current_app.config['FG_AUTH_BACKEND'].update_user(user)
db.session.commit()
def modify_user(user, password, new_password=None): def modify_user(user, password, new_password=None):

View File

@ -21,6 +21,7 @@ setup(
entry_points={ entry_points={
'flaschengeist.plugin': [ 'flaschengeist.plugin': [
'auth = flaschengeist.modules.auth:register', 'auth = flaschengeist.modules.auth:register',
'users = flaschengeist.modules.users:register',
'schedule = flaschengeist.modules.schedule:register' 'schedule = flaschengeist.modules.schedule:register'
], ],
'flaschengeist.auth': [ 'flaschengeist.auth': [