<commit_before>from __future__ import print_function
import requests
import sys
from bs4 import BeautifulSoup
import keyring
import getpass
import time
import smtplib
import re
from six.moves.email_mime_multipart import MIMEMultipart
from six.moves.email_mime_base import MIMEBase
from six.moves.email_mime_text import MIMEText
from six.moves.email_mime_base import message

# Astropy imports
from astropy.table import Table
import astropy.units as u
import astropy.coordinates as coord
import astropy.io.votable as votable
from astropy import log as logging
from astropy.io import fits
from astropy.io import votable
import astropy.utils.data as aud

# Astroquery imports
from ..utils import commons
from ..query import QueryWithLogin
from . import conf

__all__ = ['CosmoSim']

class CosmoSim(QueryWithLogin):

    QUERY_URL = conf.query_url
    SCHEMA_URL = conf.schema_url
    TIMEOUT = conf.timeout

    def __init__(self):
        super(CosmoSim, self).__init__()
        self.session = requests.session()
 
    def _login(self, username, password=None):
        
        if not hasattr(self,'session'):
            self.session = requests.session()
        self.username = username
        
        # Get password from keyring or prompt
        password_from_keyring = keyring.get_password("astroquery:www.cosmosim.org", self.username)
        if not password_from_keyring:
            logging.warning("No password was found in the keychain for the provided username.")
            if password:
                self.password = password
            else:
                self.password = getpass.getpass("{0}, enter your CosmoSim password:\n".format(self.username))
        else:
            logging.warning("Using the password found in the keychain for the provided username.")
            self.password = password_from_keyring
            
        # Authenticate
        print("Authenticating {0} on www.cosmosim.org...".format(self.username))
        authenticated = self.session.post(CosmoSim.QUERY_URL,auth=(self.username,self.password))
        if authenticated.status_code == 200:
            print("Authentication successful!")
        elif authenticated.status_code == 401:
            print("Authentication failed!")
        elif authenticated.status_code == 503:
            print("Service Temporarily Unavailable...")
            
        # Generating dictionary of existing tables
        self._existing_tables()

        if authenticated.status_code == 200 and password_from_keyring is None:
            keyring.set_password("<PASSWORD>:www.<PASSWORD>", self.username, self.password)

        # Delete job
        soup = BeautifulSoup(authenticated.content)
        if authenticated.status_code == 200:
            self.delete_job(jobid="{}".format(soup.find("uws:jobid").string),squash=True)
        
        return authenticated

    def logout(self,deletepw=True):
        """
        Public function which allows the user to logout of their cosmosim credentials.

        Parameters
        ----------
        deletepw : bool
            A hard logout - delete the password to the associated username from the keychain. The default is True.
        Returns
        -------
        """
        
        if hasattr(self,'username') and hasattr(self,'password') and hasattr(self,'session'):
            if deletepw is True:
                keyring.delete_password("<PASSWORD>:www.<PASSWORD>", self.username)
                print("Removed password for {} in the keychain.".format(self.username))
            del self.session
            del self.username
            del self.password
        else:
            logging.error("You must log in before attempting to logout.")

    def check_login_status(self):
        """
        Public function which checks the status of a user login attempt.
        """
        <commit_msg>Added login() option store_password. Also changed default behavior of deletepw (to False) for logout(), so password security is frontloaded.<commit_after>from __future__ import print_function
import requests
import sys
from bs4 import BeautifulSoup
import keyring
import getpass
import time
import smtplib
import re
from six.moves.email_mime_multipart import MIMEMultipart
from six.moves.email_mime_base import MIMEBase
from six.moves.email_mime_text import MIMEText
from six.moves.email_mime_base import message

# Astropy imports
from astropy.table import Table
import astropy.units as u
import astropy.coordinates as coord
import astropy.io.votable as votable
from astropy import log as logging
from astropy.io import fits
from astropy.io import votable
import astropy.utils.data as aud

# Astroquery imports
from ..utils import commons
from ..query import QueryWithLogin
from . import conf

__all__ = ['CosmoSim']

class CosmoSim(QueryWithLogin):

    QUERY_URL = conf.query_url
    SCHEMA_URL = conf.schema_url
    TIMEOUT = conf.timeout

    def __init__(self):
        super(CosmoSim, self).__init__()
        self.session = requests.session()
 
    def _login(self, username, password=None, store_password=False):
        
        if not hasattr(self,'session'):
            self.session = requests.session()
        self.username = username
        
        # Get password from keyring or prompt
        password_from_keyring = keyring.get_password("astroquery:www.cosmosim.org", self.username)
        if not password_from_keyring:
            logging.warning("No password was found in the keychain for the provided username.")
            if password:
                self.password = password
            else:
                self.password = getpass.getpass("{0}, enter your CosmoSim password:\n".format(self.username))
        else:
            logging.warning("Using the password found in the keychain for the provided username.")
            self.password = password_from_keyring
            
        # Authenticate
        print("Authenticating {0} on www.cosmosim.org...".format(self.username))
        authenticated = self.session.post(CosmoSim.QUERY_URL,auth=(self.username,self.password))
        if authenticated.status_code == 200:
            print("Authentication successful!")
        elif authenticated.status_code == 401:
            print("Authentication failed!")
        elif authenticated.status_code == 503:
            print("Service Temporarily Unavailable...")
            
        # Generating dictionary of existing tables
        self._existing_tables()

        if authenticated.status_code == 200 and password_from_keyring is None and store_password:
            keyring.set_password("<PASSWORD>:<PASSWORD>", self.username, self.password)

        # Delete job
        soup = BeautifulSoup(authenticated.content)
        if authenticated.status_code == 200:
            self.delete_job(jobid="{}".format(soup.find("uws:jobid").string),squash=True)
        
        return authenticated

    def logout(self,deletepw=False):
        """
        Public function which allows the user to logout of their cosmosim credentials.

        Parameters
        ----------
        deletepw : bool
            A hard logout - delete the password to the associated username from the keychain. The default is True.
        Returns
        -------
        """
        
        if hasattr(self,'username') and hasattr(self,'password') and hasattr(self,'session'):
            if deletepw is True:
                try:
                    keyring.delete_password("<PASSWORD>:<PASSWORD>", self.username)
                    print("Removed password for {} in the keychain.".format(self.username))
                except:
                    print("Password for {} was never stored in the keychain.".format(self.username))
                    
            del self.session
            del self.username
            del self.password
        else:
            logging.error("You must log in before attempting to logout.")

    def check_login_status(self):
        """
        Public function which checks the status of a user login attempt.
        """
        
{'fraction_non_alphanumeric': 0.08397707450784948, 'fraction_numerical': 0.00448542237727386, 'mean_word_length': 2.506771515945828, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, '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': '7528103', 'n_tokens_mistral': 2155, 'n_tokens_neox': 2066, 'n_words': 615}