Skip to main content

Get Current User of Drupal 9 Externally

You have a stand-alone application that is not a Drupal module but resides in a Drupal sub-folder. And you want Drupal to manage your users. You want to access the currently logged-in Drupal user from your application. The following function will give you the current  user id, name, email and roles:

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

/**
 * Get Drupal current session user details.
 * Passing Drupal folder, or its relative folder such as '..'
 * when it is called from a Drupal sub-folder.
 * Return ['id', 'name', 'email', 'roles']
 */
function get_drupal_current_user($drupal_dir) {
	// Change the directory to the Drupal root.
	chdir($drupal_dir);
	$drupal_root = getcwd();

	if ($drupal_root === false)
		return [];

	$autoloader = require_once 'autoload.php';

	$kernel = new DrupalKernel('prod', $autoloader);

	$request = Request::createFromGlobals();

	// Emulate Drupal /index.php to get the current user id
	$request->server->set("SCRIPT_FILENAME", $drupal_root . "/index.php");
	$request->server->set("REQUEST_URI", "/");
	$request->server->set("SCRIPT_NAME", "/index.php");
	$request->server->set("PHP_SELF", "/index.php");

	$response = $kernel->handle($request);
	
	$user_id = \Drupal::currentUser()->id();
	$acct = \Drupal\user\Entity\User::load($user_id);
	if ($acct != null) {
		$user_name = $acct->getDisplayName();
		$user_email = $acct->getEmail();
		$user_roles = $acct->getRoles();
	}
	else {
		$user_name = "";
		$user_email = "";
		$user_roles = [];
	}
	
	$kernel->terminate($request, $response);
	
	return ['id' => $user_id, 'name' => $user_name, 'email' => $user_email, 'roles' => $user_roles];
}

It emulates Drupal 9 index.php. It has to emulates index.php otherwise Drupal will create an anonymous session. Technically, you are already inside Drupal and you can call any Drupal function from within the code above.



Comments

Popular posts from this blog

Setting Up PyScripter for Quantum GIS

PyScripter is a general purpose Python Integrated Development Environment (IDE). Quantum GIS (QGIS) is a desktop GIS application that can be extended with Python plugins. Both are open source softwares. We intend to use PyScripter as an IDE to build QGIS Python plugin. We are using PyScripter 2.4.1.0 and QGIS 1.6.0 in Windows. PyScripter does not come with Python. On the other hand, QGIS is built in with Python. Thus, we will setup up PyScripter to use the build in Python in QGIS. We assume both PyScripter and QGIS are already installed. Preparing PyScripter batch file We assume that QGIS is installed in C:\OSGeo4W\ folder and PyScripter is installed in C:\Program Files\PyScripter\ . 1. Copy qgis.bat in C:\OSGeo4W\ bin to pyscripter.bat 2. Edit pyscripter.bat to remove the last line that read something like this start "Quantum GIS" /B "%OSGEO4W_ROOT%"\apps\qgis\bin\qgis.exe %* and replace it with this in one line Start "PyScripter" /B "C:\Progr...

Access Control

Access control is about controlling user flow within your application. Do not mistaken access control with security which is a bigger subject in itself. Access control begins by authenticating user and limit his or her activity in your application. An activity is something like creating, updating or deleting a content. There are always finite number of activities that can be done in a given application. Each user can be assigned to a set of activities that he or she is allowed to do. Access control is usually tied to session management. However, you do not need session management to have access control. When a user log in, a session is created so that the user is remembered for the subsequent access. Otherwise the user has to keep on providing his or her credential for each access. We can also keep a list of activities that the user is allowed to do in the session record. Some applications let the session alive indefinitely and some applications time out user after a duration of inacti...

Separation of Front-end and Back-end Concerns

Separation of concerns is the cornerstone of MVC framework. Model, view and controller are three broad concerns of web-based software development. On its early days MVC was implemented on server side. The server renders views for clients. Nowadays, most clients render views themselves. Even the terminology of client-server has already morphed into front-end and back-end . The need for back-end to handle views is diminishing. View concerns have became increasingly complex with two big sub-concerns of aesthetic and dynamics. Front-end evolves into bigger MVC concerns of itself. While back-end evolves into larger modeling concerns. Now, front-end and back-end are two separate concerns. Front-end and back-end are handled by two different teams of software developers with different specialties. Back-end evolves into something like "dinner can be served even without plates, forks and spoons, without table and chairs, and without a dinning room." Front-end is serving the withouts....