Example #1
0
def test_fixConfigPermissions():
    configfile = open(Auth.config, "w")
    configfile.close()

    os.chmod(Auth.config, 0000)
    assert '0000' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]
    assert True == Utils.FixFilePermissions(Auth.config)[0]
    assert '0660' == oct(os.stat(Auth.config)[stat.ST_MODE])[-4:]

    origconfig = Auth.config
    Auth.config = '/tmp/filethatdoesntexist'
    assert (False, False) == Utils.FixFilePermissions(Auth.config)
    Auth.config = origconfig
Example #2
0
def test_fixConfigOwnerships():
    configfile = open(Auth.config, "w")
    configfile.close()

    assert Utils.GetLPID() != os.stat(Auth.config).st_gid
    assert True == Utils.FixFilePermissions(Auth.config)[1]
    assert Utils.GetLPID() == os.stat(Auth.config).st_gid
Example #3
0
    def AddAccount(storage, userid=None):
        """Adds an account to the configuration file

        Args:
          storage: storage, instance of storage to store credentials in.
          userid: string, reference for the account

        Returns:
          credentials: A credentials instance with the account details
        """
        if userid == None:
            userid = raw_input(
                "Name for this user account ( eg [email protected] )? ")

        while True:
            flow = client.OAuth2WebServerFlow(
                client_id=Auth.clientid,
                client_secret=Auth.clientsecret,
                scope=['https://www.googleapis.com/auth/cloudprint'],
                user_agent=userid)
            auth_uri = flow.step1_get_authorize_url()
            print "Open this URL, grant access to CUPS Cloud Print, then provide the code displayed : \n\n" + auth_uri + "\n"
            code = raw_input('Code from Google: ')
            try:
                print ""
                credentials = flow.step2_exchange(code)
                storage.put(credentials)

                # fix permissions
                Utils.FixFilePermissions(Auth.config)

                return credentials
            except Exception as e:
                print "\nThe code does not seem to be valid ( " + str(
                    e) + " ), please try again.\n"
Example #4
0
    def AddAccountStep2(userid, flow, code, storage=None, permissions=None):
        """Executes step 2 of OAuth2WebServerFlow, without interaction.

        Args:
          userid: string, reference for the account
          permissions: string or iterable of strings, scope(s) of the credentials being requested
          storage: storage, instance of storage to store credentials in.
          flow: OAuth2WebServerFlow, flow instance
          code: string, code representing user granting CCP permission to call GCP API for user

        Returns:
          credentials: A credentials instance with the account details
        """
        if permissions is None:
            permissions = Auth.normal_permissions

        if storage is None:
            storage = multistore_file.get_credential_storage(
                Auth.config, Auth.clientid, userid, permissions)

        credentials = flow.step2_exchange(code)
        storage.put(credentials)

        Utils.FixFilePermissions(Auth.config)

        return credentials
Example #5
0
    def SetupAuth(interactive=False,
                  permissions=['https://www.googleapis.com/auth/cloudprint']):
        """Sets up requestors with authentication tokens

        Args:
          interactive: boolean, when set to true can prompt user, otherwise returns False if authentication fails

        Returns:
          requestor, storage: Authenticated requestors and an instance of storage
        """
        modifiedconfig = False

        # parse config file and extract useragents, which we use for account names
        userids = []
        if os.path.exists(Auth.config):
            content_file = open(Auth.config, 'r')
            content = content_file.read()
            data = json.loads(content)
            for user in data['data']:
                userids.append(str(user['credential']['user_agent']))
        else:
            modifiedconfig = True

        if len(userids) == 0:
            userids = [None]

        requestors = []
        for userid in userids:
            storage = multistore_file.get_credential_storage(
                Auth.config, Auth.clientid, userid, permissions)
            credentials = storage.get()

            if not credentials and interactive:
                credentials = Auth.AddAccount(storage, userid)
                modifiedconfig = True
                if userid == None:
                    userid = credentials.user_agent

            if credentials:
                # renew if expired
                requestor = cloudprintrequestor()
                if credentials.access_token_expired:
                    from oauth2client.client import AccessTokenRefreshError
                    try:
                        credentials.refresh(requestor)
                    except AccessTokenRefreshError as e:
                        sys.stderr.write(
                            "Failed to renew token (error: " + str(e) +
                            "), if you have revoked access to CUPS Cloud Print in your Google Account, please delete /etc/cloudprint.conf and re-run /usr/share/cloudprint-cups/setupcloudprint.py\n"
                        )
                        sys.exit(1)

                requestor = credentials.authorize(requestor)
                requestor.setAccount(userid)
                requestors.append(requestor)

        # fix permissions
        if modifiedconfig:
            Utils.FixFilePermissions(Auth.config)

        if not credentials:
            return False, False
        else:
            return requestors, storage
Example #6
0
    if len(sys.argv) == 2 and sys.argv[1] == 'version':
        print "CUPS Cloud Print Upgrade Script Version " + CCPVersion
        sys.exit(0)

    logging.info("Upgrading to " + CCPVersion)

    try:
        connection = cups.Connection()
    except Exception, e:
        sys.stderr.write("Could not connect to CUPS: " + e.message + "\n")
        sys.exit(0)
    cupsprinters = connection.getPrinters()

    if os.path.exists(Auth.config):
        Utils.FixFilePermissions(Auth.config)

        try:
            content_file = open(Auth.config, 'r')
            content = content_file.read()
            data = json.loads(content)
        except Exception, e:
            sys.stderr.write("Unable to read config file: " + e.message +
                             "\n\n")
            sys.exit(0)

    else:
        sys.stderr.write(
            "\nRun: /usr/share/cloudprint-cups/setupcloudprint.py to setup your Google Credentials and add your printers to CUPS\n\n"
        )
        sys.exit(0)
Example #7
0
    def SetupAuth(interactive=False, permissions=None, testUserIds=None):
        """Sets up requestors with authentication tokens

        Args:
          interactive: boolean, when set to true can prompt user, otherwise
                       returns False if authentication fails

        Returns:
          requestor, storage: Authenticated requestors and an instance
                              of storage
        """
        if permissions is None:
            permissions = Auth.normal_permissions
        modifiedconfig = False

        # parse config file and extract useragents, which we use for account
        # names
        userids = []
        if testUserIds is not None:
            userids = testUserIds
        if os.path.exists(Auth.config):
            data = json.loads(Utils.ReadFile(Auth.config))
            if 'data' in data:
                for user in data['data']:
                    userids.append(str(user['credential']['user_agent']))
        else:
            Utils.WriteFile(Auth.config, '{}')
            Utils.FixFilePermissions(Auth.config)
            modifiedconfig = True

        if len(userids) == 0:
            userids = [None]

        requestors = []
        storage = None
        credentials = None
        for userid in userids:
            if userid is not None:
                storage = multistore_file.get_credential_storage(
                    Auth.config, Auth.clientid, userid, permissions)
                credentials = storage.get()

            if not credentials and interactive:
                credentials = Auth.AddAccount(storage, userid, permissions)
                modifiedconfig = True
                if userid is None:
                    userid = credentials.user_agent

            if credentials:
                # renew if expired
                requestor = CloudPrintRequestor()
                if credentials.access_token_expired:
                    Auth.RenewToken(interactive, requestor, credentials,
                                    storage, userid)
                requestor = credentials.authorize(requestor)
                requestor.setAccount(userid)
                requestors.append(requestor)

        # fix permissions
        if modifiedconfig:
            Utils.FixFilePermissions(Auth.config)

        if not credentials:
            return False, False
        else:
            return requestors, storage