diff --git a/core/admin/mailu/manage.py b/core/admin/mailu/manage.py index e11644e7..095b9290 100644 --- a/core/admin/mailu/manage.py +++ b/core/admin/mailu/manage.py @@ -42,22 +42,44 @@ def advertise(): @click.argument('localpart') @click.argument('domain_name') @click.argument('password') +@click.option('-m', '--mode') @flask_cli.with_appcontext -def admin(localpart, domain_name, password): +def admin(localpart, domain_name, password, mode = 'create'): """ Create an admin user + 'mode' can be: + - 'create' (default) Will try to create user and will raise an exception if present + - 'ifmissing': if user exists, nothing happens, else it will be created + - 'update': user is created or, if it exists, its password gets updated """ domain = models.Domain.query.get(domain_name) if not domain: domain = models.Domain(name=domain_name) db.session.add(domain) - user = models.User( - localpart=localpart, - domain=domain, - global_admin=True - ) - user.set_password(password) - db.session.add(user) - db.session.commit() + + user = None + if mode == 'ifmissing' or mode == 'update': + email = '{}@{}'.format(localpart, domain_name) + user = models.User.query.get(email) + + if user and mode == 'ifmissing': + print('user %s exists, not updating' % email) + return + + if not user: + user = models.User( + localpart=localpart, + domain=domain, + global_admin=True + ) + user.set_password(password) + db.session.add(user) + db.session.commit() + print("created admin user") + elif mode == 'update': + user.set_password(password) + db.session.commit() + print("updated admin password") + @mailu.command() diff --git a/core/admin/start.py b/core/admin/start.py index bf0dc38f..e8de9f77 100755 --- a/core/admin/start.py +++ b/core/admin/start.py @@ -4,4 +4,12 @@ import os os.system("flask mailu advertise") os.system("flask db upgrade") + +if 'INITIAL_ADMIN_ACCOUNT' in os.environ and 'INITIAL_ADMIN_DOMAIN' in os.environ and 'INITIAL_ADMIN_PW' in os.environ: + mode = 'ifmissing' + if 'INITIAL_ADMIN_MODE' in os.environ: + mode = os.environ['INITIAL_ADMIN_MODE'] + os.system("flask mailu admin %s %s '%s' --mode %s" % ( + os.environ['INITIAL_ADMIN_ACCOUNT'], os.environ['INITIAL_ADMIN_DOMAIN'], os.environ['INITIAL_ADMIN_PW'], mode)) + os.system("gunicorn -w 4 -b :80 --access-logfile - --error-logfile - --preload 'mailu:create_app()'")