# Buggy code
def post(self, api_key_api, requester_user):
    """
    Create a new entry.
    """

    permission_type = PermissionType.API_KEY_CREATE
    rbac_utils.assert_user_has_resource_api_permission(
        user_db=requester_user,
        resource_api=api_key_api,
        permission_type=permission_type,
    )

    api_key_db = None
    api_key = None
    try:
        if not getattr(api_key_api, "user", None):
            api_key_api.user = requester_user.name or cfg.CONF.system_user.user

        try:
            User.get_by_name(api_key_api.user)
        except StackStormDBObjectNotFoundError:
            user_db = UserDB(name=api_key_api.user)
            User.add_or_update(user_db)

            extra = {"username": api_key_api.user, "user": user_db}
            LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra)

        # If key_hash is provided use that and do not create a new key. The assumption
        # is user already has the original api-key
        if not getattr(api_key_api, "key_hash", None):
            api_key, api_key_hash = auth_util.generate_api_key_and_hash()
            # store key_hash in DB
            api_key_api.key_hash = api_key_hash
        api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api))
    except (ValidationError, ValueError) as e:
        LOG.exception("Validation failed for api_key data=%s.", api_key_api)
        abort(http_client.BAD_REQUEST, str(e))

    extra = {"api_key_db": api_key_db}
    LOG.audit("ApiKey created. ApiKey.id=%s" % (api_key_db.id), extra=extra)

    api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db)
    # Return real api_key back to user. A one-way hash of the api_key is stored in the DB
    # only the real value only returned at create time. Also, no masking of key here since
    # the user needs to see this value atleast once.
    api_key_create_response_api.key = api_key

    return Response(json=api_key_create_response_api, status=http_client.CREATED)


# Traceback (AttributeError)
2017-07-18 05:36:03,099 140399285519696 ERROR router [-] Failed to call controller function "post" for operation "st2api.controllers.v1.auth:api_key_controller.post": 'NoneType' object has no attribute 'name'
Traceback (most recent call last):
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/router.py", line 414, in __call__
resp = func(**kw)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2api/controllers/v1/auth.py", line 140, in post
api_key_api.user = requester_user.name or cfg.CONF.system_user.user
AttributeError: 'NoneType' object has no attribute 'name'
2017-07-18 05:36:03,103 140399285519696 ERROR error_handling [-] API call failed: 'NoneType' object has no attribute 'name'
Traceback (most recent call last):
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/middleware/error_handling.py", line 46, in __call__
return self.app(environ, start_response)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/router.py", line 445, in as_wsgi
resp = self(req)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/router.py", line 418, in __call__
raise e
AttributeError: 'NoneType' object has no attribute 'name' (_exception_data={},_exception_class='AttributeError',_exception_message="'NoneType' object has no attribute 'name'")
2017-07-18 05:36:03,105 140399285519696 INFO logging [-] 07293032-81fe-41ea-8d4d-cdd4e0e222c6 - 500 46 7.573ms (content_length=46,request_id='07293032-81fe-41ea-8d4d-cdd4e0e222c6',runtime=7.573,remote_addr='127.0.0.1',status=500,method='POST',path='/v1/apikeys')

# Fixed code
def post(self, api_key_api, requester_user):
    """
    Create a new entry.
    """

    permission_type = PermissionType.API_KEY_CREATE
    rbac_utils.assert_user_has_resource_api_permission(
        user_db=requester_user,
        resource_api=api_key_api,
        permission_type=permission_type,
    )

    api_key_db = None
    api_key = None
    try:
        if not getattr(api_key_api, "user", None):
            if requester_user:
                api_key_api.user = requester_user.name
            else:
                api_key_api.user = cfg.CONF.system_user.user

        try:
            User.get_by_name(api_key_api.user)
        except StackStormDBObjectNotFoundError:
            user_db = UserDB(name=api_key_api.user)
            User.add_or_update(user_db)

            extra = {"username": api_key_api.user, "user": user_db}
            LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra)

        # If key_hash is provided use that and do not create a new key. The assumption
        # is user already has the original api-key
        if not getattr(api_key_api, "key_hash", None):
            api_key, api_key_hash = auth_util.generate_api_key_and_hash()
            # store key_hash in DB
            api_key_api.key_hash = api_key_hash
        api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api))
    except (ValidationError, ValueError) as e:
        LOG.exception("Validation failed for api_key data=%s.", api_key_api)
        abort(http_client.BAD_REQUEST, str(e))

    extra = {"api_key_db": api_key_db}
    LOG.audit("ApiKey created. ApiKey.id=%s" % (api_key_db.id), extra=extra)

    api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db)
    # Return real api_key back to user. A one-way hash of the api_key is stored in the DB
    # only the real value only returned at create time. Also, no masking of key here since
    # the user needs to see this value atleast once.
    api_key_create_response_api.key = api_key

    return Response(json=api_key_create_response_api, status=http_client.CREATED)