Exemple #1
0
def handle_ownership_change(model, event):
    if model.__parent__ is None:
        log.msg(
            'Ownership change event handler suppressed: model is not attached to a parent yet',
            system='ownership-change-event')
        return

    msg = 'Compute "%s" owner changed from "%s" to "%s"' % (
        model, event.oldowner, event.nextowner)
    oldowner = getUtility(IAuthentication).getPrincipal(event.oldowner)
    newowner = getUtility(IAuthentication).getPrincipal(event.nextowner)
    oldulog = UserLogger(subject=model, owner=oldowner)
    newulog = UserLogger(subject=model, owner=newowner)
    log.msg(msg, system='ownership-change-event')
    oldulog.log(msg)
    newulog.log(msg)

    try:
        submitter = IVirtualizationContainerSubmitter(model.__parent__)
        blocking_yield(
            submitter.submit(ISetOwner, model.__name__, model.__owner__))
    except Exception:
        log.err(system='ownership-change-event')
        raise

    curtransaction = transaction.get()
    curtransaction.addAfterCommitHook(update_statistics_dbhook,
                                      args=([event.oldowner,
                                             event.nextowner], ))
    def execute(self, args):
        model_cls = creatable_models.get(args.type)

        form = RawDataValidatingFactory(args.keywords,
                                        model_cls,
                                        marker=getattr(self.current_obj,
                                                       '__contains__', None))

        if form.errors:
            form.write_errors(to=self)
            return

        obj = form.create()

        vh = PreValidateHookMixin(obj)
        try:
            blocking_yield(vh.validate_hook(self.protocol.principal))
        except Exception:
            msg = 'Cancelled executing "%s" due to validate_hook failure' % self.name
            self.write('%s\n' % msg)
            log.msg(msg, system='set')
            return

        interaction = self.protocol.interaction
        if not interaction:
            auth = getUtility(IAuthentication, context=None)
            principal = auth.getPrincipal(None)
        else:
            principal = interaction.participations[0].principal

        obj.__owner__ = principal

        obj_id = self.current_obj.add(obj)

        self.write("%s\n" % obj_id)
    def execute(self, args):
        model_cls = creatable_models.get(args.type)

        form = RawDataValidatingFactory(args.keywords, model_cls,
                                        marker=getattr(self.current_obj, '__contains__', None))

        if form.errors:
            form.write_errors(to=self)
            return

        obj = form.create()

        vh = PreValidateHookMixin(obj)
        try:
            blocking_yield(vh.validate_hook(self.protocol.principal))
        except Exception:
            msg = 'Cancelled executing "%s" due to validate_hook failure' % self.name
            self.write('%s\n' % msg)
            log.msg(msg, system='set')
            return

        interaction = self.protocol.interaction
        if not interaction:
            auth = getUtility(IAuthentication, context=None)
            principal = auth.getPrincipal(None)
        else:
            principal = interaction.participations[0].principal

        obj.__owner__ = principal

        obj_id = self.current_obj.add(obj)

        self.write("%s\n" % obj_id)
Exemple #4
0
def run():
    parser = argparse.ArgumentParser(description='Manage OMS passwords')
    parser.add_argument('user', help="user name")
    parser.add_argument('-g',
                        help="group(s): comma separated list of "
                        "groups the user belongs to",
                        required=False,
                        default=None)
    parser.add_argument('-s',
                        action='store_true',
                        help="force password "
                        "prompt even if setting group(s) via -g",
                        required=False,
                        default=None)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-a', action='store_true', help="add user")
    group.add_argument('-d', action='store_true', help="delete user")
    group.add_argument('-c',
                       action='store_true',
                       help="check password, useful "
                       "to troubleshoot login issues")

    args = parser.parse_args()

    ensure_base_dir()
    passwd_file = get_config().get('auth', 'passwd_file')

    if not os.path.exists(passwd_file):
        with open(passwd_file, 'w'):
            pass

    try:
        if args.d:
            delete_user(args.user)
        elif args.a:
            add_user(args.user, ask_password(), group=args.g)
        elif args.c:
            password_checker = FilePasswordDB(passwd_file, hash=ssha_hash)
            credentials = UsernamePassword(args.user, getpass("Password: "******"Wrong credentials")

            print "ok"
        else:
            update_passwd(args.user, args.s, force=True)
    except UserManagementError as e:
        print e
        sys.exit(1)
    def render(self, request):
        log.info('Incoming authentication request from %s' % request.getClientIP())
        authentication_utility = getUtility(IHttpRestAuthenticationUtility)

        # enable basic auth only if explicitly requested
        basic_auth = request.args.get('basic_auth', [self.BASIC_AUTH_DEFAULT])[0] != 'false'

        body = request.content.getvalue()

        if request.args.get('username') and request.args.get('password'):
            credentials = UsernamePassword(request.args.get('username')[0],
                                           request.args.get('password')[0])
        elif body:
            try:
                params = json.loads(body)
            except ValueError:
                raise BadRequest("The request body not JSON-parsable")

            # cannot be unicode
            username = str(params['username'])
            password = str(params['password'])

            credentials = UsernamePassword(username, password)
        else:
            credentials = authentication_utility.get_basic_auth_credentials(request)

        # if already authenticated, return success even if the request didn't provide auth credentials
        if not credentials and request.interaction.checkPermission('rest', object):
            return {'status': 'success'}

        # XXX: refactor HttpRestServer.handle_request so that it's not a db.transact
        # so that we can use a defer.inlineCallback here
        return blocking_yield(authentication_utility.authenticate(request, credentials, basic_auth))
def run():
    parser = argparse.ArgumentParser(description='Manage OMS passwords')
    parser.add_argument('user', help="user name")
    parser.add_argument('-g', help="group(s): comma separated list of "
                        "groups the user belongs to", required=False, default=None)
    parser.add_argument('-s', action='store_true', help="force password "
                        "prompt even if setting group(s) via -g",
                        required=False, default=None)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-a', action='store_true', help="add user")
    group.add_argument('-d', action='store_true', help="delete user")
    group.add_argument('-c', action='store_true', help="check password, useful "
                       "to troubleshoot login issues")

    args = parser.parse_args()

    ensure_base_dir()
    passwd_file = get_config().get('auth', 'passwd_file')

    if not os.path.exists(passwd_file):
        with open(passwd_file, 'w'):
            pass

    try:
        if args.d:
            delete_user(args.user)
        elif args.a:
            add_user(args.user, ask_password(), group=args.g)
        elif args.c:
            password_checker = FilePasswordDB(passwd_file, hash=ssha_hash)
            credentials = UsernamePassword(args.user, getpass("Password: "******"Wrong credentials")

            print "ok"
        else:
            update_passwd(args.user, args.s, force=True)
    except UserManagementError as e:
        print e
        sys.exit(1)
Exemple #7
0
    def render(self, request, use_keystone):
        log.info('Incoming authentication request from %s' % request.getClientIP())
        auth_utility = getUtility(IHttpRestAuthenticationUtility)

        # enable basic auth only if explicitly requested
        basic_auth = request.args.get('basic_auth', [self.BASIC_AUTH_DEFAULT])[0] != 'false'

        body = request.content.getvalue()

        if request.args.get('username') and request.args.get('password'):
            credentials = UsernamePassword(request.args.get('username')[0],
                                           request.args.get('password')[0])
        elif body:
            try:
                params = json.loads(body)
            except ValueError:
                raise BadRequest("The request body is not JSON-parsable")

            # cannot be unicode
            username = str(params['username'])
            password = str(params['password'])

            credentials = UsernamePassword(username, password)
        else:
            credentials = auth_utility.get_basic_auth_credentials(request)

        if use_keystone:
            keystone_credentials = auth_utility.get_keystone_auth_credentials(request)
        else:
            keystone_credentials = None

        session = auth_utility.get_twisted_session(request)
        if not credentials and not keystone_credentials and session:
            log.debug('Authentication successful reusing valid session for %s!'
                      % ISessionStorage(session).username)
            return {'status': 'success'}
        if keystone_credentials:
            return blocking_yield(auth_utility.authenticate_keystone(request, keystone_credentials))

        # XXX: refactor HttpRestServer.handle_request so that it's not a db.transact
        # so that we can use a defer.inlineCallback here
        return blocking_yield(auth_utility.authenticate(request, credentials, basic_auth))
Exemple #8
0
def handle_ownership_change(model, event):
    msg = 'Compute "%s" owner changed from "%s" to "%s"' % (model, event.oldowner, event.nextoner)

    oldowner = getUtility(IAuthentication).getPrincipal(event.oldowner)
    newowner = getUtility(IAuthentication).getPrincipal(event.nextowner)
    oldulog = UserLogger(subject=model, owner=oldowner)
    newulog = UserLogger(subject=model, owner=newowner)
    log.msg(msg, system='ownership-change-event')
    oldulog.log(msg)
    newulog.log(msg)

    try:
        submitter = IVirtualizationContainerSubmitter(model.__parent__)
        blocking_yield(submitter.submit(ISetOwner, model.__name__, model.__owner__))
    except Exception:
        log.err(system='ownership-change-event')
        raise

    curtransaction = transaction.get()
    curtransaction.addAfterCommitHook(update_statistics_dbhook, args=([event.oldowner, event.nextowner],))
    def get_token(self, request):
        from opennode.oms.endpoint.httprest.auth import IHttpRestAuthenticationUtility

        authenticator = getUtility(IHttpRestAuthenticationUtility)

        # XXX: The following is not composable
        http_credentials = authenticator.get_basic_auth_credentials(request)
        # check if keystone token is set, if we support it
        keystone_token = authenticator.get_keystone_auth_credentials(request) \
                            if self.use_keystone_tokens else None
        if http_credentials:
            blocking_yield(authenticator.authenticate(request, http_credentials,
                                                      basic_auth=True))
            return authenticator.generate_token(http_credentials)
        elif keystone_token:
            keystone_credential = blocking_yield(authenticator.authenticate_keystone(request,
                                                                                     keystone_token))
            return keystone_credential['token']  # we expect token to be generated by the authenticator
        else:
            return authenticator.get_token(request)  # FIXME: Should not emit token here
    def get_token(self, request):
        from opennode.oms.endpoint.httprest.auth import IHttpRestAuthenticationUtility

        authenticator = getUtility(IHttpRestAuthenticationUtility)

        # XXX: The following is not composable
        http_credentials = authenticator.get_basic_auth_credentials(request)
        # check if keystone token is set, if we support it
        keystone_token = authenticator.get_keystone_auth_credentials(request) \
                            if self.use_keystone_tokens else None
        if http_credentials:
            blocking_yield(
                authenticator.authenticate(request,
                                           http_credentials,
                                           basic_auth=True))
            return authenticator.generate_token(http_credentials)
        elif keystone_token:
            keystone_credential = blocking_yield(
                authenticator.authenticate_keystone(request, keystone_token))
            return keystone_credential[
                'token']  # we expect token to be generated by the authenticator
        else:
            return authenticator.get_token(
                request)  # FIXME: Should not emit token here
    def render(self, request):
        log.info('Incoming authentication request from %s' %
                 request.getClientIP())
        authentication_utility = getUtility(IHttpRestAuthenticationUtility)

        # enable basic auth only if explicitly requested
        basic_auth = request.args.get('basic_auth',
                                      [self.BASIC_AUTH_DEFAULT])[0] != 'false'

        body = request.content.getvalue()

        if request.args.get('username') and request.args.get('password'):
            credentials = UsernamePassword(
                request.args.get('username')[0],
                request.args.get('password')[0])
        elif body:
            try:
                params = json.loads(body)
            except ValueError:
                raise BadRequest("The request body not JSON-parsable")

            # cannot be unicode
            username = str(params['username'])
            password = str(params['password'])

            credentials = UsernamePassword(username, password)
        else:
            credentials = authentication_utility.get_basic_auth_credentials(
                request)

        # if already authenticated, return success even if the request didn't provide auth credentials
        if not credentials and request.interaction.checkPermission(
                'rest', object):
            return {'status': 'success'}

        # XXX: refactor HttpRestServer.handle_request so that it's not a db.transact
        # so that we can use a defer.inlineCallback here
        return blocking_yield(
            authentication_utility.authenticate(request, credentials,
                                                basic_auth))
Exemple #12
0
def update_statistics_dbhook(success, *args):
    if success and not get_config().getboolean('stats', 'only_report_on_sync',
                                               True):
        blocking_yield(update_statistics_after_commit(*args))
Exemple #13
0
def update_statistics_dbhook(success, *args):
    if success and not get_config().getboolean('stats', 'only_report_on_sync', True):
        blocking_yield(update_statistics_after_commit(*args))
Exemple #14
0
def delete_compute(model, event):
    if ISaltInstalled.providedBy(model):
        blocking_yield(
            RejectHostRequestAction(IncomingMachineRequest(
                model.hostname)).execute(DetachedProtocol(), object()))
Exemple #15
0
def delete_compute(model, event):
    if ISaltInstalled.providedBy(model):
        blocking_yield(RejectHostRequestAction(
            IncomingMachineRequest(model.hostname)).execute(DetachedProtocol(), object()))