V8-archive: Hooks are not firing

Created on 30 Sep 2019  路  15Comments  路  Source: directus/v8-archive

Hello everyone,

I started using Directus (latest version from Github )suite on Wamp server (windows 10), and now I'm trying to check on Hooks functions in order to check later reset password option and to activate notifications.

I followed the instructions on the documentation and did exactly as it says.
This Hook.php is created on the following path C:\wamp64\www\directus\public\extensions\custom\hooks\email

image

<?php return [ 'hooks' => [ 'actions' => [ 'collection.insert.users' => function ($collection, $data) { mail("[email protected]", "New user created", "ADDED user", " Added User"); notify("[email protected]", "New user created", "ADDED user" ); }, ], 'filters' => [], ] ];
I used mail which is the library from Php to send emails, and works fine but looks like in this case it doesn't get to the hook because it doesn't do anything. Also tried with Notify but didn't do either, also trying each on them individually.

Second option i tried is to do everything on "API.PHP"
where i set up also the mail configuration which is the following.

image

'mail' => [ 'default' => [ 'transport' => 'sendmail', 'sendmail' => '', 'host' => 'smtp.gmail.com', 'port' => '587', 'username' => '[email protected]', 'password' => 'xxxxxx', 'encryption' => 'ssl', 'from' => '[email protected]' ], ],
and also tried adding my hook on this file and it didn't work either.

Here it upload a copy of the error logs as well.
error.2019-09-30.log

Maybe I'm missing some instructions. Looking forward to hearing from you.

Regards,

bug question alt stack

All 15 comments

Well if I have a look at the list of possible action hooks I don't see 'collection.insert' in that list:
https://docs.directus.io/extensions/hooks.html#creating-hooks

Maybe that is deprecated and not valid anymore.
Try 'item.create.directus_users:after' instead of 'collection.insert.users'.
I used 'item.create.directus_users:after' the day before. So I'm sure this one fires if a new user gets created.

Hello @RafaelQuintanilla
I have set up a hook to create an item in a collection and it is working fine. I am sharing my hook file code below for reference.

return [
  'actions' => [
    'item.create.companies' => function ($data, $collectionName) {
      $content = 'New company was created with the name : ' . $data['name'];
      //notify('[email protected]', 'New Article', $content);
      file_put_contents('FILEPATH/FILENAME.txt', print_r($content, true));
    }
  ]
];

It seems that your hook setup is fine but the issue might be in email settings of api.php
Can you please comment the email sending code in your hook and place file write code(take reference from above code snippet for it) to check whether the issue is in hook setup or email settings?
I have a doubt in your hook file code, you have used both notify and mail function, is it intentional or by mistake?

Hello @RafaelQuintanilla
I have set up a hook to create an item in a collection and it is working fine. I am sharing my hook file code below for reference.

return [
  'actions' => [
    'item.create.companies' => function ($data, $collectionName) {
      $content = 'New company was created with the name : ' . $data['name'];
      //notify('[email protected]', 'New Article', $content);
      file_put_contents('FILEPATH/FILENAME.txt', print_r($content, true));
    }
  ]
];

It seems that your hook setup is fine but the issue might be in email settings of api.php
Can you please comment the email sending code in your hook and place file write code(take reference from above code snippet for it) to check whether the issue is in hook setup or email settings?
I have a doubt in your hook file code, you have used both notify and mail function, is it intentional or by mistake?

Thanks for your time itsmerhp,

I used both intentionally (notify and mail) to see if one of then work..
I also tried what @PostPollux PostPollux said but didn't work either.

I Tried all these options

image


About the code you request, ill atthach it here. API.PHP**

`

return [
'app' => [
'env' => 'production',
'timezone' => 'UTC',
],

'settings' => [
    'logger' => [
        'path' => 'C:\wamp64\www\directus\src\core\Directus\Util\Installation/../../../../../logs',
    ],
],

'database' => [
    'type' => 'mysql',
    'host' => 'localhost',
    'port' => 3306,
    'name' => 'directus',
    'username' => 'rafael',
    'password' => 'rafael',
    'engine' => 'InnoDB',
    'charset' => 'utf8mb4',
    // When using unix socket to connect to the database the host attribute should be removed
    // 'socket' => '/var/lib/mysql/mysql.sock',
    'socket' => '',
],

'cache' => [
    'enabled' => false,
    'response_ttl' => 3600, // seconds
    'pool' => [
        // 'adapter' => '',
        // 'path' => '',
        // 'host' => '',
        // 'port' => '',
    ],
    // 'pool' => [
    //    'adapter' => 'apc'
    // ],
    // 'pool' => [
    //    'adapter' => 'apcu'
    // ],
    // 'pool' => [
    //    'adapter' => 'filesystem',
    //    'path' => 'cache', // relative to the api directory
    // ],
    // 'pool' => [
    //    'adapter'   => 'memcached',
    //    //'url' => 'localhost:11211;localhost:11212'
    //    'host'      => 'localhost',
    //    'port'      => 11211
    // ],
    // 'pool' => [
    //    'adapter'   => 'memcache',
    //    'url' => 'localhost:11211;localhost:11212'
    //    //'host'      => 'localhost',
    //    //'port'      => 11211
    // ],
    // 'pool' => [
    //    'adapter'   => 'redis',
    //    'host'      => 'localhost',
    //    'port'      => 6379
    // ],
],

'storage' => [
    'adapter' => 'local',
    // The storage root is the directus root directory.
    // All path are relative to the storage root when the path is not starting with a forward slash.
    // By default the uploads directory is located at the directus public root
    // An absolute path can be used as alternative.
    'root' => 'public/uploads/_/originals',
    // This is the url where all the media will be pointing to
    // here is where Directus will assume all assets will be accessed
    // Ex: (yourdomain)/uploads/_/originals
    'root_url' => '/uploads/_/originals',
    // Same as "root", but for the thumbnails
    'thumb_root' => 'public/uploads/_/thumbnails',
    // 'key' => '',
    // 'secret' => '',
    // 'region' => '',
    // 'version' => '',
    // 'bucket' => '',
    // 'options' => '',
    // Set custom S3 endpoint
    // 'endpoint' => '',
    // Use an internal proxy for downloading all files
    // 'proxy_downloads' => '',
],

'mail' => [
    'default' => [
        'transport' => 'sendmail',
        // 'sendmail' => '',
         'host' => 'smtp.gmail.com',
         'port' => '587',
         'username' => '[email protected]',
         'password' => 'xxxxxx',
         'encryption' => 'ssl',
        'from' => '[email protected]'
    ],
],

'cors' => [
    'enabled' => true,
    'origin' => array (

0 => '*',
),
'methods' => array (
0 => 'GET',
1 => 'POST',
2 => 'PUT',
3 => 'PATCH',
4 => 'DELETE',
5 => 'HEAD',
),
'headers' => array (
),
'exposed_headers' => array (
),
'max_age' => 600, // in seconds
'credentials' => false,
],

'rate_limit' => [
    'enabled' => false,
    'limit' => 100, // number of request
    'interval' => 60, // seconds
    'adapter' => 'redis',
    'host' => '127.0.0.1',
    'port' => 6379,
    'timeout' => 10,
],

'hooks' => [
    'actions' => [
    'item.create.users' => function ($data, $collectionName) {
        $content = 'New company was created with the name : ' . $data['name'];
        notify('[email protected]', 'New Article', $content);
    },
    'collection.insert.users' => function ($collection, $data) {
        mail("[email protected]", "New user created", "ADDED user", " Added User");
        notify("[email protected]", "New user created", "ADDED user" );
    },
    'item.create.articles' => function ($data, $collectionName) {
        $content = 'New article was created with the title: ' . $data['title'];
        mail('[email protected]', 'New Article', $content);
      },
    'item.create.articles' => function ($data, $collectionName) {
        $content = 'New article was created with the title: ' . $data['title'];
        mail("[email protected]", "TESTING TABLE", "ADDED ITEM", " Added User" );
      }
    ],
    'filters' => [],
],

'feedback' => [
    'token' => '0cb879c508dfec229e28a7db1e12c8e3a62a2849',
    'login' => true
],

// These tables will not be loaded in the directus schema
'tableBlacklist' => [],

'auth' => [
    'secret_key' => 'UiJw7jSNDGszJH4sJQx50BW53a3g2pln',
    'public_key' => '1a470016-1593-44bd-8056-a3e7d199ef8d',
    // 'social_providers' => '',
    // 'okta' => [
    //     'client_id' => '',
    //     'client_secret' => '',
    //     'base_url' => 'https://dev-000000.oktapreview.com/oauth2/default'
    // ],
    // 'github' => [
    //     'client_id' => '',
    //     'client_secret' => ''
    // ],
    // 'facebook' => [
    //     'client_id'          => '',
    //     'client_secret'      => '',
    //     'graph_api_version'  => 'v2.8',
    // ],
    // 'google' => [
    //     'client_id'       => '',
    //     'client_secret'   => '',
    //     'hosted_domain'   => '*',
    //     // Uses OpenIDConnect to fetch the email instead of using the Google+ API
    //     // Disabling the OIDC Mode, requires you to enable the Google+ API otherwise it will fail
    //     'use_oidc_mode'   => true,
    // ],
    // 'twitter' => [
    //     'identifier'   => '',
    //     'secret'       => ''
    // ]
],

];
`

Again, thanks a lot for your time!
Rafael

Two things jump to my eye. First, you are wrapping the return value from hooks.php in another hooks.

<?php
return [
    'hooks' => [
        'actions' => [
            'collection.insert.users' => function ($collection, $data) {
        ...

Isn't this sufficient:

<?php
return [
    'actions' => [
        'collection.insert.users' => function ($collection, $data) {
      ...

This is also what @itsmerhp has above

Second, your are giving two parameters to you function. Doesn't it just take one?

I have both actions and filters, and the former work fine, the latter don't #1364.

Two things jump to my eye. First, you are wrapping the return value from hooks.php in another hooks.

<?php
return [
    'hooks' => [
        'actions' => [
            'collection.insert.users' => function ($collection, $data) {
        ...

Isn't this sufficient:

<?php
return [
    'actions' => [
        'collection.insert.users' => function ($collection, $data) {
      ...

This is also what @itsmerhp has above

Second, your are giving two parameters to you function. Doesn't it just take one?

I have both actions and filters, and the former work fine, the latter don't #1364.

Thanks, now I understood and modified my code and I left this:

'actions' => [
        'item.create.users' => function ($data, $collectionName) {
            $content = 'New user created with the name : ' . $data['name'];
            notify('[email protected]', 'New User', $content);
        },
]

anyway I'm still getting the same, no mail sent.

About the two parameters i'm giving, it's because i'm following the Directus example from their documentation.

return [
  'actions' => [
    'item.create.articles' => function ($data, $collectionName) {
      $content = 'New article was created with the title: ' . $data['title'];
      notify('[email protected]', 'New Article', $content);
    }
  ]
];

But i got another question
is this mail configuration fine (API.PHP)?

'mail' => [
        'default' => [
            'transport' => 'sendmail',
            // 'sendmail' => '',
             'host' => 'smtp.gmail.com',
             'port' => '587',
             'username' => '[email protected]',
             'password' => 'XXXXX',
             'encryption' => 'ssl',
            'from' => '[email protected]'
        ],
    ],

I think there is some mistake in the documentation. I've got the following to work:

<?php
return [
    'filters' => [
        'item.create:before' => function(Payload $payload = null) { /* code here */ return $payload; },
        'item.update:before' =>  function(Payload $payload = null) { /* code here */ return $payload; },
        'item.read' =>  function(Payload $payload = null) { /* code here */ return $payload; }
    ],
    'actions' => [
        'item.create:after' => function($collectionName = null, $data = null) { /* code here */ },
        'item.delete:after' => function($collectionName = null, $data = null) {{ /* code here */ }
    ]
];

Importent here: the $collectionName is 1st parameter, not 2nd. So you may just have run into an exception and got an error-response from your api-call.

Also be aware that - other than the documentation implies - you can't use :after or :before in any case where the documentation states that it should work ( see #1364 ) - but this should not be the case here.

Just try changing parameters order. Also you may instantiate a logger in your code to be sure any exception/errors thrown are logged.

I think the documentation should be updated here.

Any thoughts on these issues in the docs, @bjgajjar ?

@RafaelRueda

But i got another question
is this mail configuration fine (API.PHP)?

'mail' => [
        'default' => [
            'transport' => 'sendmail',
            // 'sendmail' => '',
             'host' => 'smtp.gmail.com',
             'port' => '587',
             'username' => '[email protected]',
             'password' => 'XXXXX',
             'encryption' => 'ssl',
            'from' => '[email protected]'
        ],
    ],

Your mail configuration seems wrong. Can you please change the following options and try again.

  • 'transport' => 'smtp'
  • 'port' => '465' - For SSL encryption port should be 465 for Gmail SMTP
  • 'password' => 'XXXXX' - Are you using Application password? For Gmail smtp one must have to use an application password.

You can also verify your SMTP config here

Hooks are triggered but there's some issue in an argument which is documented in Directus Docs

@benhaynes @rijkvanzanten - I think we need to update the doc now.

As per the mention Here; hooks contain 2 arguments - collection name and data - which is partially correct. The number of arguments is based on the event. Let me explain in a brief.

 'hooks' => [
        'actions' => [
            'item.create:before' => function ($collectionName,$data) {
            },

            'item.create' => function ($collectionName,$data) {
            },

           'item.create:after' => function ($collectionName,$data) {
            },

            'item.create.collection_name:before' => function ($data) {
            },

            'item.create.collection_name' => function ($data) {
            },

            'item.create.collection_name:after' => function ($data) {
            },
        ]
    ],

As per the current structure; hooks will accept collection_name in an argument only if it's not being passed as an event name. Otherwise only data will be passed.

Can you please provide your thoughts on what should we do for this?

  1. We should update the doc with this detail
  2. We should add collection name as an argument although it's being passed as an event_name

IMO, the first option is better than the second one as when the collection_name is already passed as an event then there's no need to add it as an argument too.

Let me know your thoughts.

@benhaynes @rijkvanzanten - 馃敂 Can you please provide your thoughts on this

@bjgajjar @rijkvanzanten another opinion about hooks, if a hook is fired by a public request, the hook acl also set to public role, can we have anyway to promoted to administrator rights? so that we can read any fields of any collections of this project, code on the server side should have more more authority.

I defer to @rijkvanzanten an @WoLfulus on these technical issues. Thoughts?

@RafaelRueda make sure that you have guzzlehttp package added in your composer.json. I've had the same issue even though I had latest Directus version.

@rijkvanzanten @WoLfulus - 馃敂

Lets at least update the docs for now @bjgajjar. We need to have a long hard look at hooks sometime soon with project-scoping in mind as well.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vuhrmeister picture vuhrmeister  路  3Comments

Varulv1997 picture Varulv1997  路  3Comments

HashemKhalifa picture HashemKhalifa  路  3Comments

chintohere picture chintohere  路  3Comments

cdwmhcc picture cdwmhcc  路  3Comments