# Path: m2core/utils/data_helper.py
# class DataHelper:
#     @staticmethod
#     def random_char(length: int) -> str:
#         """
#         Generates random char sequence with the given length
#         """
#         return ''.join(random.choice(string.ascii_letters) for x in range(length))
# 
#     @staticmethod
#     def random_hex_str(length: int) -> str:
#         """
#         Generates random alpha-numeric sequence, where all chars are from hex set (a-f)
#         :param length:
#         :return:
#         """
#         return '%x' % random.randrange(16 ** length)
# 
#     @staticmethod
#     def camel_to_underline(camel) -> str:
#         """
#         Converts camelcased-string to underlined string, example:
#                 ConvertMeToUnderline -> convert_me_to_underline
#         :param camel: string to convert
#         :return: converted string
#         """
#         s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel)
#         return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
# 
# Path: m2core/data_schemes/db_system_scheme.py
# class M2Permission(BaseModel):
#     __repr_list__ = ['id', 'system_name']
# 
#     id = Column(BigInteger, primary_key=True)
#     name = Column(String(255))
#     system_name = Column(String(255), unique=True)
#     description = Column(String(500))
#     active = Column(Boolean, default=True, server_default='1')
#     created = Column(DateTime(timezone=True), server_default=text('now()'), nullable=False)
# 
#     @property
#     def enum_member(self):
#         if not hasattr(self, '__enum_member'):
#             all_perms = PermissionsEnum.all_platform_permissions
#             sys_name = self.system_name
#             for p in all_perms:
#                 if p.sys_name == sys_name:
#                     setattr(self, '__enum_member', p)
#                     return p
#             raise M2Error(f'No corresponding enum member found for Permission with sys_name=`{sys_name}`')
#         else:
#             return getattr(self, '__enum_member')
# 
#     @classmethod
#     def from_enum_member(cls, member: Permission):
#         entity = cls.s.query(M2RolePermission).filter(M2Permission.system_name == member.sys_name).first()
#         if not entity:
#             raise M2Error(f'No corresponding permission found for Permission with sys_name=`{member.sys_name}`')
# 
#         return entity
# 
# Path: m2core/common/options.py
# class M2OptionParser(OptionParser):
#     def parse_environment(self, final=True):


from m2core.utils.data_helper import DataHelper
from m2core.data_schemes.db_system_scheme import M2Permission
from m2core.common.options import options
        :param user_id: 
        :return: 
        """
        # generate token
        token = '%s_%s' % (DataHelper.random_hex_str(8), DataHelper.random_hex_str(32))
        # store in Redis in access tokens table, and also store it in user's access tokens table
        self._redis.set(
            self._redis_scheme['ACCESS_TOKENS_BY_HASH']['prefix'] % token,
            user_id,
            ex=self._redis_scheme['ACCESS_TOKENS_BY_HASH']['ttl'],
        )

        self._current_token = token
        self._current_user = user_id
        self.__inited = True

        return {
            'access_token': token,
            'expire': self._redis_scheme['ACCESS_TOKENS_BY_HASH']['ttl']
        }

    def update_token(self) -> dict:
        """
        Updates token - delete old one, generates new and stores it in Redis
        :return: 
        """
        self._check_inited()

        old_token = self._current_token
        # generate new

# Path: m2core/utils/data_helper.py
# class DataHelper:
#     @staticmethod
#     def random_char(length: int) -> str:
#         """
#         Generates random char sequence with the given length
#         """
#         return ''.join(random.choice(string.ascii_letters) for x in range(length))
# 
#     @staticmethod
#     def random_hex_str(length: int) -> str:
#         """
#         Generates random alpha-numeric sequence, where all chars are from hex set (a-f)
#         :param length:
#         :return:
#         """
#         return '%x' % random.randrange(16 ** length)
# 
#     @staticmethod
#     def camel_to_underline(camel) -> str:
#         """
#         Converts camelcased-string to underlined string, example:
#                 ConvertMeToUnderline -> convert_me_to_underline
#         :param camel: string to convert
#         :return: converted string
#         """
#         s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camel)
#         return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
# 
# Path: m2core/data_schemes/db_system_scheme.py
# class M2Permission(BaseModel):
#     __repr_list__ = ['id', 'system_name']
# 
#     id = Column(BigInteger, primary_key=True)
#     name = Column(String(255))
#     system_name = Column(String(255), unique=True)
#     description = Column(String(500))
#     active = Column(Boolean, default=True, server_default='1')
#     created = Column(DateTime(timezone=True), server_default=text('now()'), nullable=False)
# 
#     @property
#     def enum_member(self):
#         if not hasattr(self, '__enum_member'):
#             all_perms = PermissionsEnum.all_platform_permissions
#             sys_name = self.system_name
#             for p in all_perms:
#                 if p.sys_name == sys_name:
#                     setattr(self, '__enum_member', p)
#                     return p
#             raise M2Error(f'No corresponding enum member found for Permission with sys_name=`{sys_name}`')
#         else:
#             return getattr(self, '__enum_member')
# 
#     @classmethod
#     def from_enum_member(cls, member: Permission):
#         entity = cls.s.query(M2RolePermission).filter(M2Permission.system_name == member.sys_name).first()
#         if not entity:
#             raise M2Error(f'No corresponding permission found for Permission with sys_name=`{member.sys_name}`')
# 
#         return entity
# 
# Path: m2core/common/options.py
# class M2OptionParser(OptionParser):
#     def parse_environment(self, final=True):


# Path: m2core/utils/session_helper.py
from m2core.utils.data_helper import DataHelper
from m2core.data_schemes.db_system_scheme import M2Permission
from m2core.common.options import options

        :param user_id: 
        :return: 
        """
        # generate token
        token = '%s_%s' % (DataHelper.random_hex_str(8), DataHelper.random_hex_str(32))
        # store in Redis in access tokens table, and also store it in user's access tokens table
        self._redis.set(
            self._redis_scheme['ACCESS_TOKENS_BY_HASH']['prefix'] % token,
            user_id,
            ex=self._redis_scheme['ACCESS_TOKENS_BY_HASH']['ttl'],
        )

        self._current_token = token
        self._current_user = user_id
        self.__inited = True

        return {
            'access_token': token,
            'expire': self._redis_scheme['ACCESS_TOKENS_BY_HASH']['ttl']
        }

    def update_token(self) -> dict:
        """
        Updates token - delete old one, generates new and stores it in Redis
        :return: 
        """
        self._check_inited()

        old_token = self._current_token
        # generate new

        token = '%s_%s' % (DataHelper.random_hex_str(8), DataHelper.random_hex_str(32))