<commit_before># -*- coding: utf-8 -*-
"""
This module is meant to handle things related to authentication for the
Mendeley API.

In general it is better to interact with the API directly, rather than
interacting with this module.

Mendeley Authethentication Documentation:
http://apidocs.mendeley.com/home/authentication

Important Methods
-----------------
retrieve_public_authorization
retrieve_user_authorization


"""
#Standard Library
from __future__ import print_function

import pickle
import os
import sys
import datetime


#Third Party
import requests
from requests.auth import AuthBase
import pytz #This seems to be a 3rd party library but is installed on
#my local Python installation (Py Timze Zones)

#Local imports
from . import utils
from .utils import get_truncated_display_string as td
from . import config
from . import errors


#Error definitions
#-------------------------------------
def _print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


"""
-------------------------------------------------------------------------------
These are methods that other modules might want to access directly.

"""

def retrieve_public_authorization():
    """
    Loads public credentials

    Returns:
    --------
    PublicCredentials    
    """
    
    if _PublicAuthorization.token_exists_on_disk():
        return _PublicAuthorization.load()
    else:
        return _PublicAuthorization()
        
def retrieve_user_authorization(user_name=None,user_info=None,session=None):
    """
    
    """
    if _UserAuthorization.token_exists_on_disk(user_name,user_info):
        return _UserAuthorization.load(user_name,user_info,session)
    else:
        return _UserAuthorization(user_name,user_info,session)
        
"""
-------------------------------------------------------------------------------
"""

class _Authorization(AuthBase):
    
    """
    This is a superclass for:
    _UserAuthorization
    _PublicAuthorization
    
    TODO: I currently have a lot of duplicated code between the two classes that
    needs to be moved to here.
    # - get_file_path()
    # - renew_token_if_necessary()
    
    Attributes
    ----------
    token_expired : 
    expires : timestamp
    """
 
    """
    Abstract Methods
    ----------------
    renew_token
    
    """
    #The amount of time prior to token expiration that a request should be
    #made to renew the token. See self.renew_token_if_necessary()
    #I'm trying to avoid the following:
    # 1) check for valid token
    # 2) token becomes invalid
    # 3) request with invalid token
    #
    #Default value: check if there is less than 1 minute
    RENEW_TIME = datetime.timedelta(minutes = 1) 
    
    AUTH_URL = 'https://api-oauth2.mendeley.com/oauth/token'   
   
    @staticmethod
    def get_save_base_path(create_folder_if_no_exist = False):
        """
        The API credentials are stored at:
        <repo_base_path>/data/credentials
        
        NOTE: Anything in the data folder is omitted from versioning using
        .gitignore
        """
        
        if config.default_save_path is not None:
            #TODO: Ensure that this folder exists, and create if not
            return config.default_save_path
        else:
            return utils.get_save_root(['credentials'],create_folder_if_no_exist)

    @property
    def token_expired(self):        
        """
        Determine if the token has expired. As of this writing
        the token expires 1 hour after being granted.
        """
<commit_msg>bug fix on saving/loading credentials<commit_after># -*- coding: utf-8 -*-
"""
This module is meant to handle things related to authentication for the
Mendeley API.

In general it is better to interact with the API directly, rather than
interacting with this module.

Mendeley Authethentication Documentation:
http://apidocs.mendeley.com/home/authentication

Important Methods
-----------------
retrieve_public_authorization
retrieve_user_authorization


"""
#Standard Library
from __future__ import print_function

import pickle
import os
import sys
import datetime


#Third Party
import requests
from requests.auth import AuthBase
import pytz #This seems to be a 3rd party library but is installed on
#my local Python installation (Py Timze Zones)

#Local imports
from . import utils
from .utils import get_truncated_display_string as td
from . import config
from . import errors


#Error definitions
#-------------------------------------
def _print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


"""
-------------------------------------------------------------------------------
These are methods that other modules might want to access directly.

"""

def retrieve_public_authorization():
    """
    Loads public credentials

    Returns:
    --------
    PublicCredentials    
    """
    
    if _PublicAuthorization.token_exists_on_disk():
        return _PublicAuthorization.load()
    else:
        return _PublicAuthorization()
        
def retrieve_user_authorization(user_name=None,user_info=None,session=None):
    """
    
    """
    if _UserAuthorization.token_exists_on_disk(user_name,user_info):
        return _UserAuthorization.load(user_name,user_info,session)
    else:
        return _UserAuthorization(user_name,user_info,session)
        
"""
-------------------------------------------------------------------------------
"""

class _Authorization(AuthBase):
    
    """
    This is a superclass for:
    _UserAuthorization
    _PublicAuthorization
    
    TODO: I currently have a lot of duplicated code between the two classes that
    needs to be moved to here.
    # - get_file_path()
    # - renew_token_if_necessary()
    
    Attributes
    ----------
    token_expired : 
    expires : timestamp
    """
 
    """
    Abstract Methods
    ----------------
    renew_token
    
    """
    #The amount of time prior to token expiration that a request should be
    #made to renew the token. See self.renew_token_if_necessary()
    #I'm trying to avoid the following:
    # 1) check for valid token
    # 2) token becomes invalid
    # 3) request with invalid token
    #
    #Default value: check if there is less than 1 minute
    RENEW_TIME = datetime.timedelta(minutes = 1) 
    
    AUTH_URL = 'https://api-oauth2.mendeley.com/oauth/token'   
   
    @staticmethod
    def get_save_base_path(create_folder_if_no_exist = False):
        """
        The API credentials are stored at:
        <repo_base_path>/data/credentials
        
        NOTE: Anything in the data folder is omitted from versioning using
        .gitignore
        """
        
        if config.default_save_path is not None:        
            save_folder_path = os.path.join(config.default_save_path,'credentials')
            if create_folder_if_no_exist and not os.path.exists(save_folder_path):
                os.makedirs(save_folder_path)
            return save_folder_path
        else:
            return utils.get_save_root(['credentials'],create_folder_if_no_exist)

    @property
    def token_expired(self):        
        """
        Determine if the token has expired. As of this writing
        the token expires 1 hour after being granted.
        """

{'fraction_non_alphanumeric': 0.1326896551724138, 'fraction_numerical': 0.0024827586206896553, 'mean_word_length': 2.2515695067264576, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1305793', 'n_tokens_mistral': 1970, 'n_tokens_neox': 1915, 'n_words': 604}