示例#1
0
    def load(self):
        """
        Loads any data saved by a previous call to :meth:`save`.

        """

        session_file_path = config.CONFIG["session-path"]

        if os.path.isfile(session_file_path):
            logger.info("Loading session file from %s.", session_file_path)

            try:
                with open(session_file_path, "r") as f:
                    try:
                        self.user, raw_cookie_jar = pickle.load(f)
                        self.requests_session = requests.session()
                        self.requests_session.cookies = \
                            requests.utils.cookiejar_from_dict(raw_cookie_jar)
                    except:
                        logger.critical(
                            "Could not load cached request object. Try "
                            "clearing it with --logout or trying again.",
                            exc_info = sys.exc_info()
                        )

                        sys.exit(1)
            except IOError:
                logger.warn(
                    "Could not load session from %s." %
                        (session_file_path, )
                )
        else:
            logger.debug("No session file found at %s.", session_file_path)

        api_info_file_path = config.CONFIG["api-info-path"]

        if os.path.isfile(api_info_file_path):
            logger.info("Loading API Info from %s.", api_info_file_path)

            try:
                with open(api_info_file_path, "rb") as f:
                    self.api_info_raw = f.read().encode("ascii")
                    self.api_info = _parse_api_info(
                        utils.json_module().loads(self.api_info_raw)
                    )

                    logger.debug(
                        "Loaded API info...\n%s",
                        "\n".join(str(i) for i in self.api_info.values())
                    )
            except IOError:
                logger.warn(
                    "Could not load API Info from %s.",
                    api_info_file_path,
                    exc_info = sys.exc_info()
                )
示例#2
0
    def load(self):
        """
        Loads any data saved by a previous call to :meth:`save`.

        """

        session_file_path = config.CONFIG["session-path"]

        if os.path.isfile(session_file_path):
            logger.info("Loading session file from %s.", session_file_path)

            try:
                with open(session_file_path, "r") as f:
                    try:
                        self.user, raw_cookie_jar = pickle.load(f)
                        self.requests_session = requests.session()
                        self.requests_session.cookies = \
                            requests.utils.cookiejar_from_dict(raw_cookie_jar)
                    except:
                        logger.critical(
                            "Could not load cached request object. Try "
                            "clearing it with --logout or trying again.",
                            exc_info=sys.exc_info())

                        sys.exit(1)
            except IOError:
                logger.warn("Could not load session from %s." %
                            (session_file_path, ))
        else:
            logger.debug("No session file found at %s.", session_file_path)

        api_info_file_path = config.CONFIG["api-info-path"]

        if os.path.isfile(api_info_file_path):
            logger.info("Loading API Info from %s.", api_info_file_path)

            try:
                with open(api_info_file_path, "rb") as f:
                    self.api_info_raw = f.read().encode("ascii")
                    self.api_info = _parse_api_info(utils.json_module().loads(
                        self.api_info_raw))

                    logger.debug(
                        "Loaded API info...\n%s",
                        "\n".join(str(i) for i in self.api_info.values()))
            except IOError:
                logger.warn("Could not load API Info from %s.",
                            api_info_file_path,
                            exc_info=sys.exc_info())
示例#3
0
    def login_oauth2(self):
        """
        Attempts to authenticate user for Galah using Google OAuth2.

        """

        # Grab OAuth2 API keys
        logger.info("Grabbing OAuth2 API keys from Galah.")
        oauth_keys_request = self._send_api_command(
            {"api_name": "get_oauth2_keys"}
        )
        if oauth_keys_request.status_code != requests.codes.ok:
            logger.critical("Could not get OAuth2 keys from Galah.")
            sys.exit(1)
        google_api_keys = oauth_keys_request.json()
        logger.debug(
            "Galah responded with...\n%s", pprint.pformat(google_api_keys)
        )

        google = utils.rauth_module().OAuth2Service(
            client_id = google_api_keys["CLIENT_ID"],
            client_secret = google_api_keys["CLIENT_SECRET"],
            name = "google",
            authorize_url = "/o/oauth2/auth",
            access_token_url = "/o/oauth2/token",
            base_url = "https://accounts.google.com/"
        )

        # See https://developers.google.com/accounts/docs/OAuth2InstalledApp#formingtheurl
        params = {
            "scope": "https://www.googleapis.com/auth/userinfo.email",
            "response_type": "code",
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob"
        }
        if "user" in config.CONFIG:
            params["login_hint"] = config.CONFIG["user"]

        webbrowser.open(urlparse.urljoin(
            google.base_url,
            google.get_authorize_url(**params)
        ));
        # Necessary because we can't tell webbrowser not to print anything
        # to sstandard out
        time.sleep(5)
        auth_token = \
            raw_input("Please paste the token from your webbrowser: ")

        logger.debug("Trying to get access token from google.")
        access_token = google.get_access_token(
            decoder = utils.json_module().loads,
            data = {
                "code": auth_token,
                "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
                "grant_type": "authorization_code"
            },
            verify = _get_verify()
        )

        # Verify that the user succesfully logged in and figure out what email
        # they used to do it.
        token_info_request = requests.post(
            "https://www.googleapis.com/oauth2/v1/tokeninfo",
            data = {"access_token": access_token},
            verify = _get_verify()
        )
        if token_info_request.status_code != requests.codes.ok:
            logger.critical("Invalid OAuth2 login.")

            sys.exit(1)
        self.user = token_info_request.json()["email"]

        logger.debug("Trying to get an authenticated session from Galah.")

        # Use the token we got from google to initialize an authenticated
        # session on the Galah server.
        self.requests_session = requests.session()
        request = self.requests_session.post(
            urlparse.urljoin(config.CONFIG["host"], "/api/login"),
            data = {"access_token": access_token},
            verify = _get_verify()
        )
        logger.debug("Galah responded with...\n%s", request.text)
        if request.status_code != requests.codes.ok or \
                request.headers["X-CallSuccess"] != "True":
            logger.critical("Could not authenticate with Galah.")
            sys.exit(1)

        logger.info("Logged in as %s.", self.user)
示例#4
0
    def login_oauth2(self):
        """
        Attempts to authenticate user for Galah using Google OAuth2.

        """

        # Grab OAuth2 API keys
        logger.info("Grabbing OAuth2 API keys from Galah.")
        oauth_keys_request = self._send_api_command(
            {"api_name": "get_oauth2_keys"})
        if oauth_keys_request.status_code != requests.codes.ok:
            logger.critical("Could not get OAuth2 keys from Galah.")
            sys.exit(1)
        google_api_keys = oauth_keys_request.json()
        logger.debug("Galah responded with...\n%s",
                     pprint.pformat(google_api_keys))

        google = utils.rauth_module().OAuth2Service(
            client_id=google_api_keys["CLIENT_ID"],
            client_secret=google_api_keys["CLIENT_SECRET"],
            name="google",
            authorize_url="/o/oauth2/auth",
            access_token_url="/o/oauth2/token",
            base_url="https://accounts.google.com/")

        # See https://developers.google.com/accounts/docs/OAuth2InstalledApp#formingtheurl
        params = {
            "scope": "https://www.googleapis.com/auth/userinfo.email",
            "response_type": "code",
            "redirect_uri": "urn:ietf:wg:oauth:2.0:oob"
        }
        if "user" in config.CONFIG:
            params["login_hint"] = config.CONFIG["user"]

        webbrowser.open(
            urlparse.urljoin(google.base_url,
                             google.get_authorize_url(**params)))
        # Necessary because we can't tell webbrowser not to print anything
        # to sstandard out
        time.sleep(5)
        auth_token = \
            raw_input("Please paste the token from your webbrowser: ")

        logger.debug("Trying to get access token from google.")
        access_token = google.get_access_token(
            decoder=utils.json_module().loads,
            data={
                "code": auth_token,
                "redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
                "grant_type": "authorization_code"
            },
            verify=_get_verify())

        # Verify that the user succesfully logged in and figure out what email
        # they used to do it.
        token_info_request = requests.post(
            "https://www.googleapis.com/oauth2/v1/tokeninfo",
            data={"access_token": access_token},
            verify=_get_verify())
        if token_info_request.status_code != requests.codes.ok:
            logger.critical("Invalid OAuth2 login.")

            sys.exit(1)
        self.user = token_info_request.json()["email"]

        logger.debug("Trying to get an authenticated session from Galah.")

        # Use the token we got from google to initialize an authenticated
        # session on the Galah server.
        self.requests_session = requests.session()
        request = self.requests_session.post(
            urlparse.urljoin(config.CONFIG["host"], "/api/login"),
            data={"access_token": access_token},
            verify=_get_verify())
        logger.debug("Galah responded with...\n%s", request.text)
        if request.status_code != requests.codes.ok or \
                request.headers["X-CallSuccess"] != "True":
            logger.critical("Could not authenticate with Galah.")
            sys.exit(1)

        logger.info("Logged in as %s.", self.user)