From 1d11f2f645b66e6bbb7a136beff2e0bbc39bd88b Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Thu, 18 Jan 2018 21:49:53 +0100
Subject: [PATCH] Add command to run all maintenance tasks

---
 app/commands.py | 28 ++++++++++++++++++++--------
 app/tokens.py   |  1 +
 2 files changed, 21 insertions(+), 8 deletions(-)

diff --git a/app/commands.py b/app/commands.py
index e608aa5..225653a 100644
--- a/app/commands.py
+++ b/app/commands.py
@@ -48,6 +48,19 @@ def sync_user(connection, user):
     return user
 
 
+def sync_users():
+    """Synchronize all users from the database with information the LDAP server"""
+    current_app.logger.info('Synchronize database with information from the LDAP server')
+    try:
+        connection = ldap_manager.connection
+    except ldap3.core.exceptions.LDAPException as e:
+        current_app.logger.warning(f'Failed to connect to the LDAP server: {e}')
+        return
+    for user in User.query.all():
+        sync_user(connection, user)
+    db.session.commit()
+
+
 def register_cli(app):
     @app.cli.command()
     def initdb():
@@ -65,16 +78,15 @@ def register_cli(app):
     @app.cli.command()
     def syncusers():
         """Synchronize all users from the database with information the LDAP server"""
-        try:
-            connection = ldap_manager.connection
-        except ldap3.core.exceptions.LDAPException as e:
-            current_app.logger.warning(f'Failed to connect to the LDAP server: {e}')
-            return
-        for user in User.query.all():
-            sync_user(connection, user)
-        db.session.commit()
+        sync_users()
 
     @app.cli.command()
     def delete_expired_tokens():
         """Prune database from expired tokens"""
         tokens.prune_database()
+
+    @app.cli.command()
+    def maintenance():
+        """Run maintenance commands"""
+        sync_users()
+        tokens.prune_database()
diff --git a/app/tokens.py b/app/tokens.py
index 8dbb2d2..d646622 100644
--- a/app/tokens.py
+++ b/app/tokens.py
@@ -90,6 +90,7 @@ def revoke_token(token_id, user_id):
 
 def prune_database():
     """Delete tokens that have expired from the database"""
+    current_app.logger.info('Delete expired tokens')
     now = datetime.now()
     expired = models.Token.query.filter(models.Token.expires < now).all()
     for token in expired:
-- 
GitLab