Beispiel #1
0
    def execute(self, **kwargs):
        """
		Return the login name for the user currently logged in. This is typically used
		by Toolkit to resolve against the 'login' field in the Shotgun users table in order
		to extract further metadata.
		"""
        if sys.platform == "win32":
            local_username = os.environ.get("USERNAME", None)
        else:
            local_username = os.environ.get("USER", None)

            # http://stackoverflow.com/questions/117014/how-to-retrieve-name-of-current-windows-user-ad-or-local-using-python
        if os.environ.get("USERNAMESHOTGUN", None) == None:
            # return os.environ.get("USERNAME", None)
            script_name = "User_Activity"
            script_api_key = "8323196ca1dfe1aee8ec00e0b885dbae9ab02f3144daf19cd23897c85ba168d2"
            shotgun_link = 'https://rts.shotgunstudio.com'

            sg = Shotgun(shotgun_link, script_name, script_api_key)

            fields = ['login', 'tag_list']
            filters = [['login', 'is', local_username]]
            filters_alt = [['tag_list', 'is', local_username]]
            humanuser = sg.find_one("HumanUser", filters, fields)
            humanuser_alt = sg.find_one("HumanUser", filters_alt, fields)

            # If local user match with shotgun user
            if humanuser:
                return local_username
            # If local user match with shotgun alternative user
            elif humanuser_alt:
                return humanuser_alt['login']

        else:
            return os.environ.get("USERNAMESHOTGUN", None)
	def execute(self, **kwargs):
		"""
		Return the login name for the user currently logged in. This is typically used
		by Toolkit to resolve against the 'login' field in the Shotgun users table in order
		to extract further metadata.
		"""
		if sys.platform == "win32": 
			local_username = os.environ.get("USERNAME", None)
		else:
			local_username = os.environ.get("USER", None)
		
			# http://stackoverflow.com/questions/117014/how-to-retrieve-name-of-current-windows-user-ad-or-local-using-python
		if os.environ.get("USERNAMESHOTGUN", None) == None:
			# return os.environ.get("USERNAME", None)
			script_name = "User_Activity"
			script_api_key = "8323196ca1dfe1aee8ec00e0b885dbae9ab02f3144daf19cd23897c85ba168d2"
			shotgun_link = 'https://rts.shotgunstudio.com'

			sg = Shotgun(shotgun_link, script_name, script_api_key)

			fields = [ 'login','tag_list' ]
			filters = [ [ 'login', 'is', local_username ] ]
			filters_alt = [ [ 'tag_list', 'is', local_username ] ]
			humanuser = sg.find_one( "HumanUser", filters, fields )
			humanuser_alt = sg.find_one( "HumanUser", filters_alt, fields )

			# If local user match with shotgun user
			if humanuser:
				return local_username
			# If local user match with shotgun alternative user
			elif humanuser_alt:
				return humanuser_alt['login']

		else:
			return os.environ.get("USERNAMESHOTGUN", None)
def generate_session_token(hostname, login, password, http_proxy):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.

    :returns: The generated session token for that user/password/site combo.

    :raises: AuthenticationError if the credentials were invalid.
    """
    try:
        # Create the instance taht does not connect right away for speed...
        sg = Shotgun(
            hostname,
            login=login,
            password=password,
            http_proxy=http_proxy,
            connect=False
        )
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    except:
        logger.exception("There was a problem logging in.")
        raise
Beispiel #4
0
def generate_session_token(hostname, login, password, http_proxy):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.

    :returns: The generated session token for that user/password/site combo.

    :raises: AuthenticationError if the credentials were invalid.
    """
    try:
        # Create the instance taht does not connect right away for speed...
        sg = Shotgun(hostname,
                     login=login,
                     password=password,
                     http_proxy=http_proxy,
                     connect=False)
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    except:
        logger.exception("There was a problem logging in.")
        raise
Beispiel #5
0
def generate_session_token(hostname,
                           login,
                           password,
                           http_proxy,
                           auth_token=None):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.
    :param auth_token: Two factor authentication token for the user. Can be None.

    :returns: The generated session token for that user/password/auth_token/site combo.

    :raises AuthenticationError: Raised when the user information is invalid.
    :raises MissingTwoFactorAuthenticationFault: Raised when missing a two factor authentication
        code or backup code.
    :raises Exception: Raised when a network error occurs.
    """
    try:
        # Create the instance that does not connect right away for speed...
        logger.debug("Connecting to Shotgun to generate session token...")
        sg = Shotgun(hostname,
                     login=login,
                     password=password,
                     http_proxy=http_proxy,
                     connect=False,
                     auth_token=auth_token)
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    # In the following handlers, we are not rethrowing an AuthenticationError for
    # a very specific reason. While wrong credentials or host is a user
    # recoverable error, problems with proxy settings or network errors are much
    # more severe errors which can't be fixed by reprompting. Therefore, they have
    # nothing to do with authentication and shouldn't be reported as such.
    except socket.error, e:
        logger.exception("Unexpected connection error.")
        # e.message is always an empty string, so look at the exception's arguments.
        # The arguments are always a string or a number and a string.
        if isinstance(e.args[0], str):
            # if the error is just a string, simply forward the message.
            raise Exception(e.args[0])
        else:
            # We could argue here that we should only display the string portion of the
            # error since the error code is of little relevance to the user, but since
            # Toolkit doesn't properly log everything to a file at the moment, it's probably
            # safer to have the error code a little bit more in the open. Also, the formatting
            # of this exception type is pretty bad so let's reformat it ourselves. By default, it
            # turns a tuple into a string.
            raise Exception("%s (%d)" % (e.args[1], e.args[0]))
Beispiel #6
0
def generate_session_token(hostname, login, password, http_proxy, auth_token=None):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.
    :param auth_token: Two factor authentication token for the user. Can be None.

    :returns: The generated session token for that user/password/auth_token/site combo.

    :raises AuthenticationError: Raised when the user information is invalid.
    :raises MissingTwoFactorAuthenticationFault: Raised when missing a two factor authentication
        code or backup code.
    :raises Exception: Raised when a network error occurs.
    """
    try:
        # Create the instance that does not connect right away for speed...
        logger.debug("Connecting to Shotgun to generate session token...")
        sg = Shotgun(
            hostname,
            login=login,
            password=password,
            http_proxy=http_proxy,
            connect=False,
            auth_token=auth_token
        )
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    # In the following handlers, we are not rethrowing an AuthenticationError for
    # a very specific reason. While wrong credentials or host is a user
    # recoverable error, problems with proxy settings or network errors are much
    # more severe errors which can't be fixed by reprompting. Therefore, they have
    # nothing to do with authentication and shouldn't be reported as such.
    except socket.error, e:
        logger.exception("Unexpected connection error.")
        # e.message is always an empty string, so look at the exception's arguments.
        # The arguments are always a string or a number and a string.
        if isinstance(e.args[0], str):
            # if the error is just a string, simply forward the message.
            raise Exception(e.args[0])
        else:
            # We could argue here that we should only display the string portion of the
            # error since the error code is of little relevance to the user, but since
            # Toolkit doesn't properly log everything to a file at the moment, it's probably
            # safer to have the error code a little bit more in the open. Also, the formatting
            # of this exception type is pretty bad so let's reformat it ourselves. By default, it
            # turns a tuple into a string.
            raise Exception("%s (%d)" % (e.args[1], e.args[0]))
Beispiel #7
0
    def are_credentials_expired(self):
        """
        Checks if the credentials for the user are expired.

        :returns: True if the credentials are expired, False otherwise.
        """
        sg = Shotgun(self.get_host(),
                     session_token=self.get_session_token(),
                     http_proxy=self.get_http_proxy())
        try:
            sg.find_one("HumanUser", [])
            return False
        except AuthenticationFault:
            return True
Beispiel #8
0
    def are_credentials_expired(self):
        """
        Checks if the credentials for the user are expired.

        :returns: True if the credentials are expired, False otherwise.
        """
        sg = Shotgun(
            self.get_host(), session_token=self.get_session_token(),
            http_proxy=self.get_http_proxy()
        )
        try:
            sg.find_one("HumanUser", [])
            return False
        except AuthenticationFault:
            return True
Beispiel #9
0
    def are_credentials_expired(self):
        """
        Checks if the credentials for the user are expired.

        :returns: True if the credentials are expired, False otherwise.
        """
        logger.debug("Connecting to shotgun to determine if credentials have expired...")
        sg = Shotgun(
            self.get_host(),
            session_token=self.get_session_token(),
            http_proxy=self.get_http_proxy()
        )
        try:
            sg.find_one("HumanUser", [])
            return False
        except AuthenticationFault:
            return True
Beispiel #10
0
    def create_sg_connection(self):
        """
        Create a Shotgun instance using the script user's credentials.

        :returns: A Shotgun instance.
        """
        return Shotgun(self.get_host(),
                       session_token=self._session_token,
                       http_proxy=self.get_http_proxy())
Beispiel #11
0
def generate_session_token(hostname,
                           login,
                           password,
                           http_proxy,
                           auth_token=None):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.
    :param auth_token: Two factor authentication token for the user. Can be None.

    :returns: The generated session token for that user/password/auth_token/site combo.

    :raises AuthenticationError: Raised when the user information is invalid.
    :raises MissingTwoFactorAuthenticationFault: Raised when missing a two factor authentication
        code or backup code.
    """
    try:
        # Create the instance that does not connect right away for speed...
        sg = Shotgun(hostname,
                     login=login,
                     password=password,
                     http_proxy=http_proxy,
                     connect=False,
                     auth_token=auth_token)
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    except MissingTwoFactorAuthenticationFault:
        # Silently catch and rethrow to avoid logging.
        raise
    except:
        logger.exception("There was a problem logging in.")
        raise
Beispiel #12
0
    def are_credentials_expired(self):
        """
        Checks if the credentials for the user are expired.

        This check is done solely on the Shotgun side. If SSO is being used,
        we do not attempt to contact the IdP to validate the session.

        :returns: True if the credentials are expired, False otherwise.
        """
        logger.debug(
            "Connecting to shotgun to determine if credentials have expired..."
        )
        sg = Shotgun(
            self.get_host(),
            session_token=self.get_session_token(),
            http_proxy=self.get_http_proxy(),
        )
        try:
            sg.find_one("HumanUser", [])
            return False
        except ProtocolError as e:
            # One potential source of the error is that our SAML claims have
            # expired. We check if we were given a 302 and the
            # saml_login_request URL.
            # But if we get there, it means our session_token is still valid
            # as far as Shotgun is concerned.
            if (e.errcode == http_client.FOUND and "location" in e.headers
                    and e.headers["location"].endswith(
                        "/saml/saml_login_request")):
                # If we get here, the session_token is still valid.
                logger.debug(
                    "The SAML claims have expired. But the session_token is still valid"
                )
                return False
            else:
                logger.error(
                    "Unexpected exception while validating credentials: %s" %
                    e)
            return True
        except AuthenticationFault:
            return True
Beispiel #13
0
def __create_sg_connection(shotgun_cfg_path,
                           evaluate_script_user,
                           user="******"):
    """
    Creates a standard toolkit shotgun connection.

    :param shotgun_cfg_path: path to a configuration file to read settings from
    :param evaluate_script_user: if True, the id of the script user will be 
                                 looked up and returned.
    :param user: If a multi-user config is used, this is the user to create the connection for.
    
    :returns: tuple with (sg_api_instance, script_user_dict) where script_user_dict is None if
              evaluate_script_user is False else a dictionary with type and id keys. 
    """

    # get connection parameters
    config_data = __get_sg_config_data(shotgun_cfg_path, user)

    # create API
    sg = Shotgun(config_data["host"],
                 config_data["api_script"],
                 config_data["api_key"],
                 http_proxy=config_data.get("http_proxy", None))

    # bolt on our custom user agent manager
    sg.tk_user_agent_handler = ToolkitUserAgentHandler(sg)

    script_user = None

    if evaluate_script_user:
        # determine the script user running currently
        # get the API script user ID from shotgun
        script_user = sg.find_one(
            "ApiUser", [["firstname", "is", config_data["api_script"]]],
            fields=["type", "id"])
        if script_user is None:
            raise TankError(
                "Could not evaluate the current App Store User! Please contact support."
            )

    return (sg, script_user)
def generate_session_token(hostname, login, password, http_proxy, auth_token=None):
    """
    Generates a session token for a given username/password on a given site.

    :param hostname: The host to connect to.
    :param login: The user to get a session for.
    :param password: Password for the user.
    :param http_proxy: Proxy to use. Can be None.
    :param auth_token: Two factor authentication token for the user. Can be None.

    :returns: The generated session token for that user/password/auth_token/site combo.

    :raises AuthenticationError: Raised when the user information is invalid.
    :raises MissingTwoFactorAuthenticationFault: Raised when missing a two factor authentication
        code or backup code.
    """
    try:
        # Create the instance that does not connect right away for speed...
        sg = Shotgun(
            hostname,
            login=login,
            password=password,
            http_proxy=http_proxy,
            connect=False,
            auth_token=auth_token
        )
        # .. and generate the session token. If it throws, we have invalid
        # credentials or invalid host/proxy settings.
        return sg.get_session_token()
    except AuthenticationFault:
        raise AuthenticationError("Authentication failed.")
    except (ProtocolError, httplib2.ServerNotFoundError):
        raise AuthenticationError("Server %s was not found." % hostname)
    except MissingTwoFactorAuthenticationFault:
        # Silently catch and rethrow to avoid logging.
        raise
    except:
        logger.exception("There was a problem logging in.")
        raise
Beispiel #15
0
    def create_sg_connection(self):
        """
        Creates a Shotgun instance using the script user's credentials.

        :returns: A Shotgun instance.
        """
        # No need to instantiate the ShotgunWrapper because we're not using
        # session-based authentication.
        return Shotgun(
            self._host,
            script_name=self._api_script,
            api_key=self._api_key,
            http_proxy=self._http_proxy,
        )
Beispiel #16
0
    def are_credentials_expired(self):
        """
        Checks if the credentials for the user are expired.

        This check is done solely on the Shotgun side. If SSO is being used,
        we do not attempt to contact the IdP to validate the session.

        :returns: True if the credentials are expired, False otherwise.
        """
        logger.debug("Connecting to shotgun to determine if credentials have expired...")
        sg = Shotgun(
            self.get_host(),
            session_token=self.get_session_token(),
            http_proxy=self.get_http_proxy()
        )
        try:
            sg.find_one("HumanUser", [])
            return False
        except ProtocolError as e:
            # One potential source of the error is that our SAML claims have
            # expired. We check if we were given a 302 and the
            # saml_login_request URL.
            # But if we get there, it means our session_token is still valid
            # as far as Shotgun is concerned.
            if (
                e.errcode == httplib.FOUND and
                "location" in e.headers and
                e.headers["location"].endswith("/saml/saml_login_request")
            ):
                # If we get here, the session_token is still valid.
                logger.debug("The SAML claims have expired. But the session_token is still valid")
                return False
            else:
                logger.error("Unexpected exception while validating credentials: %s" % e)
            return True
        except AuthenticationFault:
            return True
Beispiel #17
0
def __create_sg_connection(shotgun_cfg_path, evaluate_script_user, user="******"):
    """
    Creates a standard toolkit shotgun connection.

    :param shotgun_cfg_path: path to a configuration file to read settings from
    :param evaluate_script_user: if True, the id of the script user will be 
                                 looked up and returned.
    :param user: If a multi-user config is used, this is the user to create the connection for.
    
    :returns: tuple with (sg_api_instance, script_user_dict) where script_user_dict is None if
              evaluate_script_user is False else a dictionary with type and id keys. 
    """

    # get connection parameters
    config_data = __get_sg_config_data(shotgun_cfg_path, user)

    # create API
    sg = Shotgun(config_data["host"],
                 config_data["api_script"],
                 config_data["api_key"],
                 http_proxy=config_data.get("http_proxy", None))

    # bolt on our custom user agent manager
    sg.tk_user_agent_handler = ToolkitUserAgentHandler(sg)

    script_user = None

    if evaluate_script_user:
        # determine the script user running currently
        # get the API script user ID from shotgun
        script_user = sg.find_one("ApiUser",
                                          [["firstname", "is", config_data["api_script"]]],
                                          fields=["type", "id"])
        if script_user is None:
            raise TankError("Could not evaluate the current App Store User! Please contact support.")

    return (sg, script_user)
def generate_schema(sg_url, sg_script, sg_key, schema_file_path, schema_entity_file_path):
    """
    Helper method for mockgun.
    Generates the schema files needed by the mocker by connecting to a real shotgun
    and downloading the schema information for that site. Once the generated schema 
    files are being passed to mockgun, it will mimic the site's schema structure.
    
    :param sg_url: Shotgun site url
    :param sg_script: Script name to connect with
    :param sg_key: Script key to connect with
    :param schema_file_path: Path where to write the main schema file to
    :param schema_entity_file_path: Path where to write the entity schema file to
    """
    sg = Shotgun(sg_url, sg_script, sg_key)
    
    schema = sg.schema_read()
    fh = open(schema_file_path, "w")
    pickle.dump(schema, fh)
    fh.close()
        
    schema_entity = sg.schema_entity_read()
    fh = open(schema_entity_file_path, "w")
    pickle.dump(schema_entity, fh)
    fh.close()
Beispiel #19
0
    def create_sg_connection(self):
        """
        Create a Shotgun instance using the script user's credentials.
        :returns: A Shotgun instance.
        """
        # Delay the connection so that we can adjust the Config manually.
        shotgun_obj = Shotgun(
            self.get_host(),
            session_token=self._session_token,
            connect=False,
            http_proxy=self._http_proxy
        )
        # The API must be notified that the session token in this case is the
        # result of an RV licensing request.
        shotgun_obj.config.extra_auth_params = { "product": "rv" }
        shotgun_obj.server_caps

        return shotgun_obj
Beispiel #20
0
        config_data = file_data

    # validate the config data to ensure all fields are present
    if "host" not in config_data:
        raise TankError("Missing required field 'host' in config '%s'" %
                        shotgun_cfg_path)
    if "api_script" not in config_data:
        raise TankError("Missing required field 'api_script' in config '%s'" %
                        shotgun_cfg_path)
    if "api_key" not in config_data:
        raise TankError("Missing required field 'api_key' in config '%s'" %
                        shotgun_cfg_path)

    # create API
    sg = Shotgun(config_data["host"],
                 config_data["api_script"],
                 config_data["api_key"],
                 http_proxy=config_data.get("http_proxy", None))

    script_user = None

    if evaluate_script_user:
        # determine the script user running currently
        # get the API script user ID from shotgun
        script_user = sg.find_one(
            "ApiUser", [["firstname", "is", config_data["api_script"]]],
            fields=["type", "id"])
        if script_user is None:
            raise TankError(
                "Could not evaluate the current App Store User! Please contact support."
            )
Beispiel #21
0
        config_data = file_data

    # validate the config data to ensure all fields are present
    if "host" not in config_data:
        raise TankError("Missing required field 'host' in config '%s'" %
                        shotgun_cfg_path)
    if "api_script" not in config_data:
        raise TankError("Missing required field 'api_script' in config '%s'" %
                        shotgun_cfg_path)
    if "api_key" not in config_data:
        raise TankError("Missing required field 'api_key' in config '%s'" %
                        shotgun_cfg_path)

    # create API
    sg = Shotgun(config_data["host"],
                 config_data["api_script"],
                 config_data["api_key"],
                 http_proxy=config_data.get("http_proxy", None))

    # bolt on our custom user agent manager
    sg.tk_user_agent_handler = ToolkitUserAgentHandler(sg)

    script_user = None

    if evaluate_script_user:
        # determine the script user running currently
        # get the API script user ID from shotgun
        script_user = sg.find_one(
            "ApiUser", [["firstname", "is", config_data["api_script"]]],
            fields=["type", "id"])
        if script_user is None:
            raise TankError(
Beispiel #22
0
        config_data = file_data[user]
    else:
        # old format - not grouped by user
        config_data = file_data
        
    # validate the config data to ensure all fields are present
    if "host" not in config_data:
        raise TankError("Missing required field 'host' in config '%s'" % shotgun_cfg_path)
    if "api_script" not in config_data:
        raise TankError("Missing required field 'api_script' in config '%s'" % shotgun_cfg_path)
    if "api_key" not in config_data:
        raise TankError("Missing required field 'api_key' in config '%s'" % shotgun_cfg_path)

    # create API
    sg = Shotgun(config_data["host"],
                 config_data["api_script"],
                 config_data["api_key"],
                 http_proxy=config_data.get("http_proxy", None))

    # bolt on our custom user agent manager
    sg.tk_user_agent_handler = ToolkitUserAgentHandler(sg)

    script_user = None

    if evaluate_script_user:
        # determine the script user running currently
        # get the API script user ID from shotgun
        script_user = sg.find_one("ApiUser",
                                          [["firstname", "is", config_data["api_script"]]],
                                          fields=["type", "id"])
        if script_user is None:
            raise TankError("Could not evaluate the current App Store User! Please contact support.")