Drupal user authentication check

358 Views Asked by At

I have been trying to write a function to check if user is authenticated and then call a google analytics script for custom report. This has been a big hassle and I believe Drupal is not that difficult. Is there anyone who can help or take up the project? It should be a simple and straight forward thing to do but being able to check user authentication has not been easy

I've tried to use a php function to check if user is logged in but I was not able to call javascript function from it.

I wrote a script function with jquery calling the script on page load but I was not able to check if user is logged in using javascript

1

There are 1 best solutions below

0
donbuche On

Maybe it's not the best option, but...

  1. What do you think about calling, from your JS function, a custom module's controller, that return true if... $currentUser = \Drupal::currentUser(); $uid = $currentUser->id(); returns a numeric value higher than 0 or false if the value returned is 0 (anonymous user)? This controller only should had to return the UID of the current user in a JSON format, readable afterwards from your JS.

  2. Another try would be to write a YOURTHEMENAME_preprocess_page() function in your theme's .theme file that implement the above check, and send the value to the template, in order to render the value in a 'data-attribute' in some DOM element. Once rendered, you could access the value from your JS.

None of these approachs are 'Drupal way' of doing the stuff, but... hope these help you.

Cheers.