[packagekit] PolicyKit dbus interfacing

Martin Pitt martin.pitt at ubuntu.com
Wed Aug 6 22:48:31 PDT 2008

Hi Aidan,

Aidan Skinner [2008-08-06 23:05 +0100]:
> Right, I'm probably being a numpty, but I just cannot get my head around
> this.

BTW, maybe you find the complete function useful:

-------- snip -----------
class PermissionDeniedByPolicy(dbus.DBusException):
    _dbus_error_name = 'com.ubuntu.DeviceDriver.PermissionDeniedByPolicy'

def polkit_auth_wrapper(fn, *args, **kwargs):
    '''Function call wrapper for PolicyKit authentication.

    Call fn(*args, **kwargs). If it fails with a PermissionDeniedByPolicy
    and the caller can authenticate to get the missing privilege, the PolicyKit
    authentication agent is called, and the function call is attempted again.
        return fn(*args, **kwargs)
    except dbus.DBusException, e:
        if e._dbus_error_name == PermissionDeniedByPolicy._dbus_error_name:
            # last words in message are privilege and auth result
            (priv, auth_result) = e.message.split()[-2:]
            if auth_result.startswith('auth_'):
                pk_auth = dbus.Interface(dbus.SessionBus().get_object(
                    'org.freedesktop.PolicyKit.AuthenticationAgent', '/', False),
                # TODO: provide xid
                res = pk_auth.ObtainAuthorization(priv, dbus.UInt32(0),
                    dbus.UInt32(os.getpid()), timeout=300)
                if res:
                    return fn(*args, **kwargs)
            raise PermissionDeniedByPolicy(priv + ' ' + auth_result)

-------- snip -----------

(You have to use your project specific PermissionDeniedByPolicy class,
of course)

If you use this wrapper, then using polkit-protected calls becomes
very convenient:

  result = my_dbus_proxy_object.method_name(arg1, arg2, namedarg='foo')


  result = polkit_auth_wrapper(my_dbus_proxy_object.method_name, arg1, arg2, namedarg='foo')


Martin Pitt                        | http://www.piware.de
Ubuntu Developer (www.ubuntu.com)  | Debian Developer  (www.debian.org)

More information about the PackageKit mailing list