예제 #1
0
 def login_with_token(self, token=None):
     if token:
         logging.debug("Using Token for login.")
         cookie_obj = requests.cookies.create_cookie(
             domain='.geocaching.com', name='gspkauth', value=token)
         self._session.cookies.set_cookie(cookie_obj)
         logging.debug("Checking the result.")
         logged_user = self.get_logged_user()
         if logged_user:
             logging.info(
                 "Logged in successfully as {}.".format(logged_user))
             self._logged_in = True
             self._logged_username = logged_user
             return
         else:
             self.logout()
             raise LoginFailedException(
                 "Cannot login to the site "
                 "(probably wrong username or password).")
예제 #2
0
    def login(self, username=None, password=None):
        """Log in the user for this instance of Geocaching.

        If username or password is not set, try to load credentials from file. Then load login page
        and do some checks about currently logged user. As a last thing post the login form and
        check result.

        :param str username: User's username or :code:`None` to use data from credentials file.
        :param str password: User's password or :code:`None` to use data from credentials file.
        :raise .LoginFailedException: If login fails either because of bad credentials or
            non-existing credentials file.
        """
        logging.info("Logging in...")

        if not username or not password:
            try:
                username, password = self._load_credentials()
            except FileNotFoundError as e:
                raise LoginFailedException(
                    "Credentials file not found and "
                    "no username and password is given.") from e
            except ValueError as e:
                raise LoginFailedException(
                    "Wrong format of credentials file.") from e
            except KeyError as e:
                raise LoginFailedException(
                    "Credentials file doesn't contain "
                    "username or password/password_cmd.") from e
            except IOError as e:
                raise LoginFailedException(
                    "Credentials file reading error.") from e
            except subprocess.CalledProcessError as e:
                raise LoginFailedException(
                    "Error calling password retrieval command.") from e

        logging.debug("Checking for previous login.")
        if self._logged_in:
            logging.info("Already logged in as {}.".format(
                self._logged_username))
            if self._logged_username == username:
                return
            else:
                logging.info(
                    "Want to login as {} => logging out.".format(username))
                self.logout()

        login_page = self._request(self._urls["login_page"], login_check=False)

        # continue logging in, assemble POST
        logging.debug("Assembling POST data.")
        token_field_name = "__RequestVerificationToken"
        token_value = login_page.find("input",
                                      attrs={"name":
                                             token_field_name})["value"]
        post = {
            "Username": username,
            "Password": password,
            token_field_name: token_value
        }

        # login to the site
        logging.debug("Submiting login form.")
        after_login_page = self._request(self._urls["login_page"],
                                         method="POST",
                                         data=post,
                                         login_check=False)

        logging.debug("Checking the result.")
        if self.get_logged_user(after_login_page):
            logging.info("Logged in successfully as {}.".format(username))
            self._logged_in = True
            self._logged_username = username
            return
        else:
            self.logout()
            raise LoginFailedException(
                "Cannot login to the site "
                "(probably wrong username or password).")
예제 #3
0
    def login(self, username, password):
        """Logs the user in.

        Downloads the relevant cookies to keep the user logged in."""

        logging.info("Logging in...")

        try:
            login_page = self._browser.get(self._urls["login_page"])
        except requests.exceptions.ConnectionError as e:
            raise Error("Cannot load login page.") from e

        logging.debug("Checking for previous login.")
        logged = self.get_logged_user(login_page)
        if logged:
            if logged == username:
                logging.info("Already logged as %s.", logged)
                self._logged_in = True
                return
            else:
                logging.info("Already logged as %s, but want to log in as %s.",
                             logged, username)
                self.logout()

        # continue logging in
        post = {}
        logging.debug("Assembling POST data.")

        # login fields
        login_elements = login_page.soup.find_all(
            "input", type=["text", "password", "checkbox"])
        post.update({
            field["name"]: val
            for field, val in zip(login_elements, [username, password, 1])
        })

        # other nescessary fields
        other_elements = login_page.soup.find_all("input",
                                                  type=["hidden", "submit"])
        post.update(
            {field["name"]: field["value"]
             for field in other_elements})

        # login to the site
        logging.debug("Submiting login form.")

        try:
            after_login_page = self._browser.post(self._urls["login_page"],
                                                  post)
        except requests.exceptions.ConnectionError as e:
            raise Error(
                "Cannot load response after submiting login form.") from e

        logging.debug("Checking the result.")
        if self.get_logged_user(after_login_page):
            logging.info("Logged in successfully as %s.", username)
            self._logged_in = True
            return
        else:
            self.logout()
            raise LoginFailedException(
                "Cannot login to the site (probably wrong username or password)."
            )
예제 #4
0
    def login(self, username=None, password=None):
        """Log in the user for this instance of Geocaching.

        If username or password is not set, try to load credentials from file. Then load login page
        and do some checks about currently logged user. As a last thing post the login form and
        check result.

        :param str username: User's username or :code:`None` to use data from credentials file.
        :param str password: User's password or :code:`None` to use data from credentials file.
        :raise .LoginFailedException: If login fails either because of bad credentials or
            non-existing credentials file.
        """
        if not username or not password:
            try:
                username, password = self._load_credentials()
            except FileNotFoundError as e:
                raise LoginFailedException(
                    "Credentials file not found and "
                    "no username and password is given.") from e
            except ValueError as e:
                raise LoginFailedException(
                    "Wrong format of credentials file.") from e
            except KeyError as e:
                raise LoginFailedException(
                    "Credentials file doesn't "
                    "contain username and password.") from e
            except IOError as e:
                raise LoginFailedException(
                    "Credentials file reading error.") from e

        logging.info("Logging in...")
        login_page = self._request(self._urls["login_page"], login_check=False)

        logging.debug("Checking for previous login.")
        logged = self.get_logged_user(login_page)
        if logged:
            if logged == username:
                logging.info("Already logged as {}.".format(logged))
                self._logged_in = True
                return
            else:
                logging.info(
                    "Already logged as {}, but want to log in as {}.".format(
                        logged, username))
                self.logout()

        # continue logging in
        post = {}
        logging.debug("Assembling POST data.")

        # login fields
        login_elements = login_page.find_all(
            "input", type=["text", "password", "checkbox"])
        post.update({
            field["name"]: val
            for field, val in zip(login_elements, [username, password, 1])
        })

        # other nescessary fields
        other_elements = login_page.find_all("input",
                                             type=["hidden", "submit"])
        post.update(
            {field["name"]: field["value"]
             for field in other_elements})

        # login to the site
        logging.debug("Submiting login form.")
        after_login_page = self._request(self._urls["login_page"],
                                         method="POST",
                                         data=post,
                                         login_check=False)

        logging.debug("Checking the result.")
        if self.get_logged_user(after_login_page):
            logging.info("Logged in successfully as {}.".format(username))
            self._logged_in = True
            return
        else:
            self.logout()
            raise LoginFailedException(
                "Cannot login to the site "
                "(probably wrong username or password).")