|
14 | 14 | import re |
15 | 15 | import uuid |
16 | 16 |
|
17 | | -from datetime import datetime |
| 17 | +from datetime import datetime, timedelta |
18 | 18 | import hashlib |
19 | 19 | from typing import Optional |
20 | 20 |
|
|
32 | 32 | from .database.config_db_model import OAuthToken |
33 | 33 | from .database.config_db_model import PersonalAccessToken |
34 | 34 | from .database.config_db_model import SystemPermission |
| 35 | +from .database.database import DBSession |
35 | 36 | from .permissions import SUPERUSER |
36 | 37 |
|
37 | 38 | import codechecker_api_shared |
@@ -858,6 +859,25 @@ def __create_local_session(self, token, user_name, groups, is_root, |
858 | 859 | self.__refresh_time, is_root, self.__config_db_sessionmaker, |
859 | 860 | last_access) |
860 | 861 |
|
| 862 | + def __cleanup_expired_auth_sessions(self, user_name: str): |
| 863 | + """ |
| 864 | + Cleanup expired auth_sessions of a user from the database. |
| 865 | + """ |
| 866 | + with DBSession(self.__config_db_sessionmaker) as session: |
| 867 | + try: |
| 868 | + cutoff_date = (datetime.now() - timedelta( |
| 869 | + seconds=self.__auth_config['session_lifetime'])) |
| 870 | + session.query(SessionRecord) \ |
| 871 | + .filter(SessionRecord.user_name == user_name) \ |
| 872 | + .filter(SessionRecord.last_access < cutoff_date) \ |
| 873 | + .delete(synchronize_session=False) |
| 874 | + |
| 875 | + session.commit() |
| 876 | + except Exception as e: |
| 877 | + LOG.error("Failed to cleanup expired auth sessions " |
| 878 | + "from the database:") |
| 879 | + LOG.error(str(e)) |
| 880 | + |
861 | 881 | def create_session(self, auth_string): |
862 | 882 | """ Creates a new session for the given auth-string. """ |
863 | 883 | if not self.__auth_config['enabled']: |
@@ -889,6 +909,9 @@ def create_session(self, auth_string): |
889 | 909 | groups = validation.get('groups', []) |
890 | 910 | is_root = validation.get('root', False) |
891 | 911 |
|
| 912 | + if user_name: |
| 913 | + self.__cleanup_expired_auth_sessions(user_name) |
| 914 | + |
892 | 915 | local_session = self.__create_local_session(token, user_name, |
893 | 916 | groups, is_root) |
894 | 917 | self.__sessions.append(local_session) |
@@ -953,6 +976,8 @@ def create_session_oauth(self, provider: str, |
953 | 976 | 'groups': groups, |
954 | 977 | 'is_root': False} |
955 | 978 |
|
| 979 | + self.__cleanup_expired_auth_sessions(username) |
| 980 | + |
956 | 981 | local_session = self.__create_local_session( |
957 | 982 | codechecker_session_token, |
958 | 983 | user_data.get('username'), |
|
0 commit comments